Part 04 / Topic 4 of 6
HAVING
WHERE filters rows before grouping. HAVING filters groups after aggregation — it is the only place you can test an aggregate. Statuses with more than one order:
SELECT status, count(*) AS orders
FROM orders
GROUP BY status
HAVING count(*) > 1
ORDER BY orders DESC;
status | orders
-----------+--------
delivered | 6
(1 row)
Both clauses together, each doing its own job — among orders placed from February on, which statuses still have more than one?
SELECT status, count(*) AS orders
FROM orders
WHERE order_date >= '2025-02-01'
GROUP BY status
HAVING count(*) > 1;
status | orders
-----------+--------
delivered | 4
(1 row)
WHERE threw out January's rows before counting; HAVING threw out small groups after. Swap them in your head and the numbers change — the Part 2 evaluation order (FROM → WHERE → GROUP BY → HAVING → SELECT) is doing the work here.
(Putting a row condition in HAVING instead of WHERE usually still runs — but it makes the database group rows it could have discarded early, and it reads as confusion. Row conditions belong in WHERE; group conditions belong in HAVING.)
🧪 Quick quiz — answer from memory, then check.
- Which clause can test
count(*) > 5, and why not the other? - "Delivered orders per city, but only cities with 3+ delivered orders" — where does each condition go?
Show the answers
- HAVING — aggregates don't exist yet when WHERE runs.
WHERE status = 'delivered'(row test),HAVING count(*) >= 3(group test).
Done here? The practice set for Part 4 — 7 exercises with solutions — is on the part page.