Learning navigation

Code with Animation

HAVING vs WHERE

Filter rows before grouping with WHERE and filter whole groups after counting with HAVING, and know which test belongs where.

SQL5 min readConcept 21 of 44

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.

SELECT team, count(*) AS n, round(avg(points), 1) AS avg_points
FROM players
GROUP BY team
HAVING count(*) >= 3;
players (8 rows)
nametextteamtextpointsintegergroup
AshaRed31Red
BenBlue17Blue
ChenRedNULLRed
DaraGreen24Green dropped
EliBlueNULLBlue
FayRed24Red
GusGreen40Green dropped
HanaBlue17Blue
Result (2 rows)
teamtextnbigintavg_pointsnumeric
Red327.5
Blue317

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.

  1. 1Which query keeps only the teams that have at least 3 players?
  2. 2`WHERE points IS NOT NULL` is added to a query with `HAVING count(*) >= 3`. In the players data, what changes for Red, which had 3 players with one NULL?
  3. 3You want only the Red team's average. Why is `WHERE team = 'Red'` better than `HAVING team = 'Red'`?

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.