HAVING vs WHERE
Filter rows before grouping with WHERE and filter whole groups after counting with HAVING, and know which test belongs where.
Two filters at two moments
WHERE filters individual rows before they are grouped. HAVING filters whole groups after the aggregates are computed.
That timing decides what each one can see. WHERE can only look at single rows, so it cannot use an aggregate. HAVING looks at groups, so it normally tests an aggregate such as count(*).
Different questions need different filters
"Only count players who have a score" is a question about rows. "Only show teams with at least 3 players" is a question about groups. Using the wrong filter either fails or quietly gives a different answer.
Teams with at least 3 players
SELECT team, count(*) AS n
FROM players
GROUP BY team
HAVING count(*) >= 3;Red and Blue have 3 players each, and Green has 2, so the result is Red and Blue. Green was a real group, but HAVING removed it after counting.
Now add WHERE points IS NOT NULL before GROUP BY. WHERE removes Chen and Eli first, so every team has only 2 rows left, and HAVING count(*) >= 3 removes all three teams. The result is empty. Same data, different order of filters, different answer.
Combine WHERE and HAVING
Try each WHERE together with each HAVING and read the source table: rows removed by WHERE are greyed out, and groups removed by HAVING say dropped. Then press WHERE count(*) >= 3.
| nametext | teamtext | pointsinteger | group |
|---|---|---|---|
| Asha | Red | 31 | Red |
| Ben | Blue | 17 | Blue |
| Chen | Red | NULL | Red |
| Dara | Green | 24 | Green dropped |
| Eli | Blue | NULL | Blue |
| Fay | Red | 24 | Red |
| Gus | Green | 40 | Green dropped |
| Hana | Blue | 17 | Blue |
| teamtext | nbigint | avg_pointsnumeric |
|---|---|---|
| Red | 3 | 27.5 |
| Blue | 3 | 17 |
Without WHERE, Red and Blue have 3 players each (the NULL ones count), so they pass HAVING count(*) >= 3. Green has 2 and is dropped.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- WHERE filters rows before grouping. HAVING filters groups after the aggregates are computed.
- An aggregate in WHERE is an error: at that time no groups exist yet.
- Put tests on plain columns in WHERE, and tests on aggregates in HAVING.
- A WHERE test can change a group's count, so it can change what HAVING sees.
Done with this concept?
Mark it complete to track your progress. No login needed.