HAVING filters the groups
WHERE tests one row at a time, so it runs before any grouping and can't talk about a group's total. HAVING runs after the groups are made and tests each group as a whole. That's how you keep only the classes with more than five students.
A tiny example
In plain English: For each class, tell me how many students are in it, but only show classes with more than five.
SELECT class_id, COUNT(*) AS students
FROM students
GROUP BY class_id
HAVING COUNT(*) > 5;What comes back
| class_id | students |
|---|---|
| 2 | 9 |
| 3 | 7 |
Class 1 exists too, but with only 4 students it fails the HAVING test of more than 5, so it's not here.
Related SQL lessons
Ready for a break?
Take on today's cozy puzzle. A fresh, bite-sized query waits every morning — no timers, no pressure.
play today's sip