Beginner8 min reading time

SELECT: choosing columns and rows

Retrieve exactly the columns and rows you need with SELECT and WHERE, and see how the same filter is expressed in MongoDB.

SELECT * is convenient, but real queries usually ask for specific columns and filter to specific rows. Two clauses do most of the work: the *select list* (which columns) and the WHERE clause (which rows).

Choosing columns

Return only the columns you need

List column names instead of *. This is portable ANSI SQL and behaves identically everywhere.

SELECT first_name, last_name, email
FROM employees;

Filtering rows with WHERE

Only employees in the Sales department

The WHERE clause keeps only the rows that match a condition. String literals use single quotes in standard SQL.

SELECT first_name, last_name
FROM employees
WHERE department = 'Sales';

The same filter in MongoDB

Sales employees, selected fields only

SQL (relational)

SELECT first_name, last_name
FROM employees
WHERE department = 'Sales';

MongoDB (document)

db.employees.find(
  { department: "Sales" },
  { first_name: 1, last_name: 1, _id: 0 }
);

The first argument to find() is the filter (your WHERE). The second argument is a projection (your select list): 1 includes a field, and _id: 0 suppresses the id MongoDB would otherwise return by default.