Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

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.

  1. Which clause can test count(*) > 5, and why not the other?
  2. "Delivered orders per city, but only cities with 3+ delivered orders" — where does each condition go?
Show the answers
  1. HAVING — aggregates don't exist yet when WHERE runs.
  2. 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.

Search the guide