HAVING — Filtering Groups in SQL
A WHERE for aggregated results
HAVING filters groups after aggregation, the way WHERE filters rows before it. “Show departments whose average salary exceeds 60,000” is impossible in WHERE (averages don’t exist yet there) — trivial with HAVING AVG(salary) > 60000. Sequence: WHERE → group → aggregate → HAVING → select.
WHERE cannot see aggregates
WHERE runs before grouping — AVG(salary) does not exist yet there.
HAVING filters groups
GROUP BY department HAVING AVG(salary) > 60000 — the condition is evaluated per finished bucket.
Any aggregate condition works
HAVING COUNT(*) >= 2 finds groups with at least two members; SUM/MIN/MAX are equally legal.
WHERE and HAVING coexist
WHERE narrows rows first; HAVING narrows groups after — both in one query is normal.
Execution order is fixed
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY — memorise it once, debug forever.
1SELECT department, COUNT(*) AS headcount,2 ROUND(AVG(salary), 0) AS avg_salary3FROM employees4GROUP BY department5HAVING AVG(salary) > 60000;
| department | headcount | avg_salary |
|---|---|---|
| Engineering | 3 | 83000 |
Sales (55k) and Marketing (47k) fail the threshold after grouping; Engineering alone survives. Slide the threshold in the visualization and watch buckets drop.
Average-salary threshold
Keep groups whose average clears 60000.
1SELECT department,2 COUNT(*) AS headcount,3 ROUND(AVG(salary), 0) AS avg_salary4FROM employees5GROUP BY department6HAVING AVG(salary) > 60000;
| department | headcount | avg_salary |
|---|---|---|
| Engineering | 3 | 83000 |
Group-size filter
Only groups with at least 2 members.
1SELECT department, COUNT(*) AS headcount2FROM employees3GROUP BY department4HAVING COUNT(*) >= 2;
| department | headcount |
|---|---|
| Engineering | 3 |
| Sales | 2 |
WHERE + HAVING together
Rows filtered first, groups filtered second.
1SELECT department, COUNT(*) AS headcount2FROM employees3WHERE salary >= 500004GROUP BY department5HAVING COUNT(*) >= 2;
| department | headcount |
|---|---|
| Engineering | 3 |
| Sales | 2 |
HAVING without GROUP BY
The whole table becomes one group.
1SELECT COUNT(*) AS n2FROM employees3HAVING COUNT(*) > 3;
| n |
|---|
| 6 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.