SQL 101· Level 5
HAVING
WHERE filters rows before they are grouped, so it cannot use a count or an average: those do not exist yet. HAVING filters the groups afterwards.
WHEREasks a question about each row:WHERE year = 2025.HAVINGasks a question about each group:HAVING COUNT(*) > 100.
A query can use both. The rows are filtered by WHERE, then grouped, then the groups are filtered by HAVING.
Clause order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
A quick test: if the condition mentions COUNT, SUM, AVG, MIN or MAX, it belongs in HAVING. Otherwise it belongs in WHERE.
Worked example
Which units have had more than 120 enrolments?
SELECT unit_code, COUNT(*) AS enrolments FROM enrolments GROUP BY unit_code HAVING COUNT(*) > 120 ORDER BY enrolments DESC
Getting the practice database ready…
This takes a few seconds the first time. Nothing leaves your computer.