Welcome to HAVING! Last time we learned GROUP BY to organize data into groups. But what if you only want groups that meet certain criteria?
HAVING lets you filter groups based on their calculated totals, averages, or counts.
Engagement Message
When might you want only customers who made more than 5 purchases?
Here's the key difference: WHERE filters individual rows before grouping, while HAVING filters groups after they're created and calculated.
WHERE asks "Which rows qualify?" HAVING asks "Which groups qualify?"
Engagement Message
If you want customers with total orders over $500, would you use WHERE or HAVING?
HAVING always comes after GROUP BY in your SQL statement. The order is: SELECT, FROM, WHERE, GROUP BY, HAVING.
This makes sense because you need groups first before you can filter them by their aggregate values.
Engagement Message
Why must HAVING come after GROUP BY in the statement order?
Let's see HAVING in action. This query finds customers who placed more than 3 orders:
Only customer groups with more than 3 orders appear in results.
Engagement Message
What would happen if we changed the condition to HAVING COUNT(*) >= 2?
You can use any aggregate function in HAVING conditions. Find customers who spent over $1000 total:
