WHERE filters rows; HAVING filters groups
Starting table: cookies
| shape | price |
|---|---|
| leaf | 4 |
| leaf | 5 |
| acorn | 3 |
| star | 5 |
It all comes down to what you are inspecting. First, WHERE filters individual rows before grouping happens — like setting aside cookies under $4. Next, GROUP BY puts the remaining cookies into tins by shape — all the leaf cookies together, and all the star cookies together. Finally, HAVING filters the groups after they are formed — like keeping only tins that hold more than one cookie. Yes, WHERE and HAVING can work together in the same query.
A tiny example
In plain English: Keep cookies priced at least $4, group them by shape, then show only shapes with more than one cookie remaining.
SELECT shape, COUNT(*)
FROM cookies
WHERE price >= 4
GROUP BY shape
HAVING COUNT(*) > 1;What comes back
| shape | COUNT(*) |
|---|---|
| leaf | 2 |
WHERE leaves the $4 leaf, $5 leaf and $5 star. GROUP BY makes a leaf group of 2 and a star group of 1. HAVING keeps the leaf group and excludes the star group. The $3 acorn was already excluded by WHERE; the stored cookies table stays unchanged.
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