← All lessons
SQL from zero · Lesson 4 of 10

Several conditions

AND joins two conditions and keeps a row only if both are true. Garden products under 30:

SELECT name, price
FROM products
WHERE category = 'Garden' AND price < 30;
Returns
name        | price
------------+------
Duck feeder | 24
Pond net    | 12.5
(2 rows)

OR keeps a row if either one is true (or both):

SELECT name, city
FROM customers
WHERE city = 'Boston' OR city = 'Denver';
Returns
name | city
-----+-------
Ben  | Denver
Dev  | Boston
Eve  | Denver
Gus  | Boston
(4 rows)

When you mix them, AND is worked out before OR, the way multiplying comes before adding in arithmetic. Put brackets around the part that should go together. Books or garden things, and in either case under 15:

SELECT name, category, price
FROM products
WHERE (category = 'Books' OR category = 'Garden') AND price < 15;
Returns
name       | category | price
-----------+----------+------
Pond net   | Garden   | 12.5
Sketchbook | Books    | 9.75
(2 rows)

Without the brackets, the database reads it as "Books, or Garden things under 15", and the field guide at 18 sneaks in. When you mix AND and OR, add brackets even when you think you don't need them.

IN is a short way to write several ORs on one column: city IN ('Boston', 'Denver') means the same as the OR query above. BETWEEN checks a range, and includes both ends:

SELECT name, price
FROM products
WHERE price BETWEEN 20 AND 50;
Returns
name        | price
------------+------
Duck feeder | 24
Bird bath   | 45.5
Rain boots  | 40
(3 rows)

NOT turns a condition around: NOT category = 'Garden' keeps everything that isn't Garden, and NOT IN and NOT BETWEEN work the same way.

Practice

Garden products that cost more than 20: 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

a AND bBoth must be true.
a OR bEither one (or both).
NOT aThe opposite of a.
( … )Group conditions; AND goes before OR without them.
x IN (1, 2, 3)x is any of the values in the list.
x BETWEEN a AND bFrom a to b, both included.

The other AI and data engineering courses