Part 02 / Topic 4 of 9
Combining conditions: AND, OR, NOT
Real questions have several parts. AND requires both, OR accepts either, NOT flips:
SELECT name, price, stock
FROM products
WHERE price < 100 AND stock > 0;
name | price | stock
--------------------+-------+-------
SQL for Beginners | 35.00 | 100
Postgres Deep Dive | 55.00 | 60
Chef Knife | 80.00 | 30
Desk Lamp | 45.00 | 12
USB-C Cable | 15.00 | 200
(5 rows)
AND binds tighter than OR — like multiplication before addition. This query means something you probably didn't intend:
SELECT name, category_id, price FROM products
WHERE category_id = 4 OR category_id = 5 AND price < 500;
name | category_id | price
---------------+-------------+---------
Laptop Pro 14 | 4 | 1200.00
Laptop Air 13 | 4 | 950.00
Phone Lite | 5 | 399.00
(3 rows)
That returned all laptops (category 4) — even the 1200.00 one — because Postgres read it as category_id = 4 OR (category_id = 5 AND price < 500). Parentheses say what you meant:
SELECT name, category_id, price FROM products
WHERE (category_id = 4 OR category_id = 5) AND price < 500;
name | category_id | price
------------+-------------+--------
Phone Lite | 5 | 399.00
(1 row)
The rule that saves you: the moment a WHERE mixes AND with OR, add parentheses — even when they match what precedence would do anyway. Future-you reads intentions, not precedence tables.
🧪 Quick quiz — answer from memory, then check.
- Which binds tighter, AND or OR?
- Rewrite
a OR b AND cso it reads unambiguously, keeping the same meaning.
Show the answers
- AND.
a OR (b AND c).
Done here? The practice set for Part 2 — 8 exercises with solutions — is on the part page.