← All lessons
SQL from zero · Lesson 3 of 10

Picking rows with WHERE

SELECT chooses columns. To choose rows, add a WHERE clause after FROM. It holds a condition: a test that each row either passes or fails. Only the rows that pass come back.

SELECT name, price
FROM products
WHERE category = 'Garden';
Returns
name        | price
------------+------
Duck feeder | 24
Bird bath   | 45.5
Pond net    | 12.5
(3 rows)

Text values go inside single quotes: 'Garden'. Without them the database would think Garden was the name of a column. Numbers don't need quotes:

SELECT name, price
FROM products
WHERE price > 40;
Returns
name       | price
-----------+------
Bird bath  | 45.5
Raincoat   | 59
Binoculars | 120
(3 rows)

The tests you can use:

  • = equal to
  • <> not equal to (!= works in most databases too)
  • < less than, > more than
  • <= less than or equal to, >= more than or equal to

Text has to match exactly. 'garden' with a small g finds nothing here, because when you compare text with =, capital letters count.

Dates in this database are stored as text in the form year-month-day, like '2024-09-15'. Written that way, earlier dates come first in alphabetical order, so < and > work on them: < means before and > means after. The orders placed in October or later:

SELECT id, ordered_on
FROM orders
WHERE ordered_on >= '2024-10-01';
Returns
id  | ordered_on
----+-----------
107 | 2024-10-02
108 | 2024-10-05
109 | 2024-10-07
110 | 2024-10-11
(4 rows)

You can filter on a column you don't show. The database finds the table, keeps the rows that pass, and then picks the columns you asked for:

SELECT name
FROM products
WHERE price < 20;
Returns
name
-----------
Pond net
Field guide
Sketchbook
(3 rows)

Practice

The products in the Clothing category: their name and price.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

WHERE conditionKeep only the rows where the condition is true.
= <> < > <= >=Equal, not equal, less, more, and the or-equal versions.
'text'Text values go in single quotes; numbers don't.
'2024-09-15'Dates as year-month-day text compare in time order.

The other AI and data engineering courses