skipnothing/SQL

HAVING vs WHERE

Six orders rows, two of them refunded: drop the refunds and you have filtered rows. Keep only buyers whose remaining total tops 50, though, and the filter waits for a number that does not exist yet.

  • ▸Drop the refunds first and only four rows ever reach the grouping step, not six.
  • ▸SUM(amount) > 50 in WHERE is rejected: the total isn't computed until grouping is done.
  • ▸The same SUM(amount) > 50 runs one clause later, once each buyer's total exists.
BUILDS ON
01

WHERE fires before the collapse

The six rows in orders carry a status: four are paid, two are refunded. To total only the paid orders for each buyer, drop the refunds first. Their amounts are blank here, so SUM would skip them anyway, but dropping them leaves fewer rows to fold. That is a row test (a predicate, judged one row at a time): keep it when status = 'paid', drop it otherwise. WHERE status = 'paid' does exactly that, and it does it before any grouping happens. Other row tests work the same way: user_id <> 3 (<> means not equal) keeps every row whose user_id is not 3, so only buyers 1 and 2 reach the grouping step.

That 'before' is not a preference. A query's clauses run in a fixed sequence, the execution order, and it is not the order you type them: the engine works through FROM, then WHERE, then GROUP BY, then a slot for a second filter that a later part fills, then SELECT, then ORDER BY. So WHERE fires at the second station, while the rows are still separate and full-width, well before GROUP BY folds them into one row per buyer.

That sequence is the whole reason WHERE is a row filter. When it runs, no group exists yet and no total exists yet; there is only the raw row in front of it. Drop the two refunds here and four rows reach the grouping step instead of six, and cutting rows this early means fewer rows to fold.

TWO STATIONS, ONE COLLAPSE BETWEEN THEM

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL