$ settings --editor

$ settings --general

$ save --settings

SQL for beginners

Filtering rows with WHERE #

So far, every query we've written returns every row in a table. The WHERE clause lets us keep only the rows that match a condition, filtering out the rest.

Syntax #

SELECT
    column_name
FROM
    table_name
WHERE
    condition;

condition: An expression that is checked for every row. Only rows where the condition is true are included in the result.

Example #

SELECT
    *
FROM
    customers;

returns all 10 rows. If we only want the customers whose gender is 'F', we add a WHERE clause:

SELECT
    *
FROM
    customers
WHERE
    gender = 'F';

Result:

+----+------------+-----------+-----+--------+
| id | first_name | last_name | age | gender |
+----+------------+-----------+-----+--------+
| 2  |  Jonathan  |   Dixon   | 71  |   F    |
| 4  |    Juan    |  Campos   | 99  |   F    |
| 6  |    Kyle    |   Blair   | 62  |   F    |
| 8  |   Tammy    |   Woods   | 86  |   F    |
+----+------------+-----------+-----+--------+

Notice that WHERE comes right after FROM, and before any ORDER BY or LIMIT clause.


Exercise #

Write a query that retrieves all columns from the customers table, keeping only the rows where gender is 'F'.

  • The result has a gender column.
  • The result contains exactly the rows where gender is 'F', and no others.
Solution
SELECT
    *
FROM
    customers
WHERE
    gender = 'F';
Output will be displayed here