GROUP BY deals the rows into buckets; aggregates summarise each bucket; HAVING then throws away buckets you do not want.
1 GROUP BY buckets
Rows sharing a value — same city, same dept — land in the same bucket before counting.
2 One row per bucket
Each bucket collapses into a single summary row in the result.
3 WHERE vs HAVING
WHERE filters rows BEFORE grouping; HAVING filters the finished groups AFTER.
4 HAVING needs aggregates
Conditions like COUNT(*) >= 2 make sense only per group — that is the job of HAVING.
Buckets, counts, and the group filter
GROUP BY buckets1Rows sharing a value — same city, same dept — land in the same bucket before counting.
One row per bucket2Each bucket collapses into a single summary row in the result. WHERE vs HAVING3WHERE filters rows BEFORE grouping; HAVING filters the finished groups AFTER. HAVING needs aggregates4Conditions like COUNT(*) >= 2 make sense only per group — that is the job of HAVING.
4 building blocks make up Buckets, counts, and the group filter
Press play: rows are bucketed by city, counted, then HAVING drops every bucket with fewer than 2 rows.
SELECT city, COUNT(*)
FROM students
GROUP BY city
HAVING COUNT(*) >= 2;
students
| id | name | score | city |
|---|
| 1 | Ava | 92 | Oslo |
| 2 | Ben | 82 | Oslo |
| 3 | Chloe | 85 | Lima |
| 4 | Dev | 68 | Lima |
| 5 | Emma | 95 | Oslo |
| 6 | Finn | 88 | Paris |
| city | COUNT(*) |
|---|
| press play — rows will appear here |
Step 1/6GROUP BY city buckets the rows: the Oslo bucket catches Ava, Ben and Emma.
Click through the assembly line: every clause hands its output to the next — and HAVING only sees groups.
The full assembly line at work: group, judge, sort. What does the client print?
Your predicted output — one line per console line
Hint: HAVING drops the tiny Paris group first; then ORDER BY sorts the survivors A to Z.
Click a keyword, then click its job to lock the pair.
5 conceptsTap a card to expand ?GROUP BYdrops into place
?HAVINGdrops into place
?WHEREdrops into place
?COUNT(*)drops into place
?One row per groupdrops into place
01GROUP BY deals rows into buckets; every bucket emits exactly one row.
02WHERE filters rows before grouping; HAVING filters groups after.
03If your condition uses COUNT, SUM or AVG, it belongs in HAVING.
04The result has one row per surviving group — not one per source row.
05ORDER BY sorts the finished summary rows and always runs last.