HAVING
In one line
HAVING filters groups created by GROUP BY — it is like WHERE, but applied after aggregation rather than before.
In simple words
HAVING is like WHERE, but for groups. WHERE filters individual rows before they are grouped; HAVING filters groups after they have been created by GROUP BY.
The key difference: you cannot use aggregate functions in WHERE (because rows have not been grouped yet), but you can in HAVING. For example, you cannot write WHERE COUNT(*) > 5, but you can write HAVING COUNT(*) > 5.
A common pattern is: filter rows with WHERE, group with GROUP BY, then filter groups with HAVING.
Example
-- Users who placed more than 5 orders
SELECT user_id, COUNT(*) AS order_count
FROM orders
WHERE status = 'completed'
GROUP BY user_id
HAVING COUNT(*) > 5;WHERE filters to completed orders, GROUP BY groups by user, HAVING keeps only groups with more than 5.
Related terms
Related Resources
Related Lessons
- GROUP BY
Learn GROUP BY and HAVING together.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.