GROUP BY vs HAVING (and where WHERE fits)
WHERE filters rows, HAVING filters groups. One query at a time, here is the execution order and the mistakes it prevents.
GROUP BY vs HAVING (and where WHERE fits)
WHERE and HAVING both filter, which is why they get confused. The difference is when they run: before or after the rows become groups.
Groups first, filters second
Count the tracks in each genre:
SELECT genre_id, COUNT(*) AS tracks
FROM tracks
GROUP BY genre_id
ORDER BY tracks DESC;
Eight rows come back, one per genre. Rock has 11, Soul 9, Folk 8, and three genres have only 3.
Now keep only the genres with more than five tracks:
SELECT genre_id, COUNT(*) AS tracks
FROM tracks
GROUP BY genre_id
HAVING COUNT(*) > 5
ORDER BY tracks DESC;
Five rows remain: Rock (11), Soul (9), Folk (8), Jazz (6) and Electronic (6). HAVING had to wait until the counts existed.
WHERE runs before the groups exist
WHERE filters rows, so it runs before GROUP BY. This query only counts full-price tracks:
SELECT genre_id, COUNT(*) AS tracks
FROM tracks
WHERE unit_price = 1.29
GROUP BY genre_id
HAVING COUNT(*) >= 2
ORDER BY tracks DESC;
The WHERE throws away every 0.99 track before the piles are built. Then HAVING drops the genres that still have fewer than two full-price tracks. Five genres survive: Rock, Soul, Jazz, Electronic and Classical.
If you tried to write WHERE COUNT(*) > 5, the database would reject it: at that point there are no counts yet.
The execution order
A useful mental model for a query with grouping:
FROM/JOIN— build the rows.WHERE— drop rows.GROUP BY— split the rest into groups.HAVING— drop groups.SELECT— compute the output columns.ORDER BY— sort the result.LIMIT— cut it.
That is also why you cannot use a SELECT alias in WHERE, but you often can in ORDER BY.
A rule you can keep
If the condition mentions a raw column, it can go in WHERE. If it mentions COUNT, SUM, AVG, MIN or MAX, it must go in HAVING. When in doubt, put row filters in WHERE — fewer rows reach the grouping step, which is usually faster.
Keep exploring: the aggregates chapter covers COUNT, SUM, AVG, MIN, MAX and HAVING with seven graded exercises.