SQL HAVING: filter groups, not rows
WHERE removes rows before grouping. HAVING removes whole groups after it.
SQL skills · Summaries
What you will learn
If a condition uses COUNT, SUM or another aggregate, it belongs in HAVING.
Both can be in one query: WHERE first, then GROUP BY, then HAVING.
The basics
HAVING filters groups after they are made. It is the WHERE of grouped results and can use aggregates.
SELECT region, COUNT(*)
FROM invoices
WHERE status = 'Overdue'
GROUP BY region
HAVING COUNT(*) > 3WHERE or HAVING?
WHERE removes single rows before grouping, so it cannot use COUNT or SUM. HAVING removes whole groups after grouping. A condition on a plain column belongs in WHERE; a condition on a total belongs in HAVING.
Full order
SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. That is the order you write them in, and nearly the order the database runs them.
Worked examples
Example 1
Regions with more than three overdue invoices.
SELECT region, COUNT(*)
FROM invoices
WHERE status = 'Overdue'
GROUP BY region
HAVING COUNT(*) > 3WHERE keeps overdue rows, HAVING keeps big groups.
Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.
Try a taskCommon mistakes
- Writing WHERE COUNT(*) > 3, which is an error.
- Putting a plain row condition in HAVING. It may work but it is slower and confusing.
- Placing HAVING before GROUP BY.
Where you will use it at work
- Sales: reps with more than ten won deals.
- Support: agents whose average response time is over an hour.
- Finance: customers whose open balance is over $20,000.
Questions people ask
Can HAVING use a column alias?
In PostgreSQL, MySQL, SQLite and Snowflake often yes; to be safe, repeat the aggregate.
Can I use HAVING without GROUP BY?
Yes, then the whole table is one group, but it is rare.
What is the full clause order?
SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
Ready to write it yourself?
Practice Filter groups with HAVING