SQL HAVING
HAVING filters groups after aggregation. It's WHERE for the output of GROUP BY.
Example
SQL
SELECT country, COUNT(*) AS customers FROM customers GROUP BY country HAVING COUNT(*) > 5 ORDER BY customers DESC;
"Show countries that have more than 5 customers" — the filter is on the aggregate result, which WHERE can't see.
WHERE vs HAVING
| Need to filter | Use |
|---|---|
| Individual rows before grouping | WHERE |
| Whole groups after aggregation | HAVING |
| Both | Both — WHERE first, then HAVING |
SQL
SELECT country, COUNT(*) AS active_customers FROM customers WHERE active = 1 -- per-row filter GROUP BY country HAVING COUNT(*) >= 10; -- per-group filter
Common pitfall
Putting an aggregate in WHERE is a syntax error:
SQL
-- ✗ Error: aggregate not allowed in WHERE WHERE COUNT(*) > 5 -- ✓ Move it to HAVING HAVING COUNT(*) > 5
Tip: If
HAVING only references columns in GROUP BY (not aggregates), prefer WHERE — it filters earlier and is usually faster.Example
Example
SELECT country, COUNT(*) AS customers FROM customers GROUP BY country HAVING COUNT(*) > 5;Try it Yourself »
Exercise
Filter the groups, keeping only those with more than 5 customers.
GROUP BY country
COUNT(*) > 5
Six letters; WHERE for groups.
Discussion
Loading…