HAVING — Filtering Groups
HAVING filters groups after GROUP BY using aggregate conditions, while WHERE filters individual rows before grouping.
Compare filtering individual rows with filtering completed group summaries.
The marketing team wants "customers who have bought more than three items in total". You cannot write WHERE SUM(quantity) > 3, because when WHERE runs, the totals do not exist yet. HAVING is WHERE's partner for the moment after grouping.
The rule
WHERE filters rows before grouping; HAVING filters groups after.
| order_id | customer_id | product_id | quantity | status |
|---|---|---|---|---|
| 101 | 1 | 1 | 2 | shipped |
| 102 | 2 | 3 | 1 | pending |
| 103 | 1 | 2 | 5 | shipped |
| 104 | 3 | 1 | 1 | cancelled |
| 105 | 3 | 2 | 3 | shipped |
SELECT customer_id, SUM(quantity) AS items
FROM orders
GROUP BY customer_id
HAVING SUM(quantity) > 3;The groups are customer 1 (7 items), customer 2 (1) and customer 3 (4). HAVING keeps groups whose total is over 3: customers 1 and 3.
The full order the database follows now makes sense of everything in this section:
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY
- WHERE sees individual rows, so it can test
statusbut notSUM(quantity). - HAVING sees whole groups, so it tests aggregates, or the grouping columns themselves.
- ORDER BY runs last and can sort by an aggregate or its alias:
ORDER BY items DESC.
Some databases (MySQL, SQLite) also let HAVING use the SELECT alias, as in HAVING items > 3, but PostgreSQL and SQL Server do not. Repeating the aggregate works everywhere.