SQL Topic
HAVING
HAVING filters groups after aggregation, exactly like WHERE filters rows before it. Any condition on an aggregate — a count above 5, an average above the company average — belongs in HAVING.
When is HAVING used?
Finding duplicate values (HAVING COUNT(*) > 1), groups that exceed a threshold, or comparing a group aggregate to another aggregate.
Core syntax
SELECT col FROM table GROUP BY col HAVING COUNT(*) > 1 — HAVING can reference aggregates and aliases.Common mistakes
- Writing WHERE COUNT(*) > 1 (aggregates are not allowed in WHERE).
- Repeating the whole aggregate expression instead of using the alias in HAVING.
- Forgetting that HAVING runs after GROUP BY, so it cannot filter individual rows.
Practice HAVING questions
Work through them in order — each question builds on the last.