GROUP BY combines rows that share a value, such as one row per city. HAVING then filters those groups, while WHERE filters individual rows before grouping.
The order matters
- WHERE removes rows you do not want.
- GROUP BY forms the groups.
- HAVING keeps only the groups that pass a test, such as total sales above a set amount.
Example
To find cities with more than five orders, group the orders table by city, count the rows, and use HAVING COUNT(*) greater than 5. Using WHERE for the same test fails, because WHERE cannot see the count.
Check your answer on a small table first. Start with SQL basics for data analysts, then window functions. Book a free demo class, and ask a counsellor for batch details.
