skip to content

the order a query actually runs in

FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. the most important picture in SQL.

address
everything.basics.logical_order
part
part 2, one table
chapter
chapter 9 of 12
reading time
12 min

a SELECT is written in one order and runs in another: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. every clause takes a table and hands a table to the next one.

that's the whole chapter. the rest is pictures.

the picture

you know how you can ORDER BY an alias but can't use it in WHERE? kinda cursed. it stops being cursed the moment you see that the clauses don't run in the order you typed them.

think of a kitchen line. every station gets a tray (a table) and passes a tray on. the first one fetches the ingredients (FROM). the next bins the bad ones (WHERE). then everything gets sorted into bowls (GROUP BY), bowls with too little in them get tossed (HAVING), each bowl becomes a plate and the dish gets its name (SELECT), the plates get lined up (ORDER BY), and the first three go out (LIMIT).

  1. FROM200 × 9
    fetch the ingredients
  2. WHERE188 × 912 rows out
    bin the bad ones
  3. GROUP BY11 groups
    sort into bowls
  4. HAVING10 groups1 group out
    toss the small bowls
  5. SELECT10 × 3aliases born
    plate up, name the dishes
  6. ORDER BY10 × 3by avg_price
    line the plates up
  7. LIMIT3 × 37 rows out
    serve three
real output, postgres 18.6 (PGlite 0.5.12) · logical-order
one query, seven stations, and the shape of the tray each one passes on. taller means more rows (on a square-root scale, so 200 and 3 fit), wider means more columns. dashed is what a station threw out.

notice that nothing ever goes back to an earlier station. a tray only ever moves on, and each station works on the tray it was handed. that one rule explains every alias error you'll ever get: a clause can only see what the stations before it produced.

walk through it

here's the query from the figure: the three priciest categories, counting only products still on sale, and only categories with at least 10 of them.

query.sqldb=shop
SELECT category, count(*) AS n, round(avg(price), 2) AS avg_price
FROM products
WHERE NOT discontinued
GROUP BY category
HAVING count(*) >= 10
ORDER BY avg_price DESC
LIMIT 3;
output, from postgres 18.6
SELECT 3
categorytextnint8avg_pricenumeric
audio20123.34
pets16117.64
bath25106.35
(3 rows)

now take it apart. press step (or click the figure and use ← →). every table under the query is a real intermediate result, captured from the same postgres that runs on this page.

query.sqlstep 1: FROM
  1. 1SELECT category, count(*) AS n, round(avg(price), 2) AS avg_price
  2. 2FROM products
  3. 3WHERE NOT discontinued
  4. 4GROUP BY category
  5. 5HAVING count(*) >= 10
  6. 6ORDER BY avg_price DESC
  7. 7LIMIT 3;
the table after FROM
idint4categorytextpricenumericdiscontinuedboolnametext
8pets89.00tcat tree
17kitchen21.55tspare grater
34games148.19tretro go board
51bath153.30tsmart shower caddy
68kitchen194.97tbamboo saucepan
85office71.44ttravel desk lamp
102kitchen128.13tfolding kettle
119bath28.65tlinen bath mat
136kitchen129.18theavy whisk
153office23.74tbamboo stapler
170outdoor77.67tdeluxe water bottle
187audio49.70tlinen earbuds
1kitchen49.00fchef's knife
2kitchen39.50fcast iron pan
… 186 more
(200 rows)

FROM hands over all 200 products. a table has no order of its own, so they're drawn with the 12 discontinued ones on top, where you can watch them go.

the query that produced this table
SELECT id, category, price, discontinued, name FROM products ORDER BY discontinued DESC, id
clause 1/7
real output, postgres 18.6 (PGlite 0.5.12) · logical-order
rows a clause throws out stay for one step, struck through, then they're gone. GROUP BY buckets alternate shades, with the NULL bucket on top. the table shows 5 of products' 9 columns: id, the 3 the query reads, and name.

see? n and avg_price don't exist until the SELECT station. WHERE ran three stations earlier, HAVING one station earlier. that's why HAVING has to say count(*) again instead of n: from where HAVING stands, nobody has handed out the name n yet.

and look at what HAVING threw out. the 3 products with no category landed in one bucket together, which is odd if you remember that NULL = NULL isn't true. GROUP BY doesn't ask =, it asks "are these the same?", and for grouping, two NULLs are. more on that split personality in NULL and three-valued logic.

predict the output
sql
SELECT name, price * 1.2 AS gross
FROM products
WHERE gross > 100;

here it is failing for real:

sqldb=shop
SELECT name, price * 1.2 AS gross
FROM products
WHERE gross > 100;
output, from postgres 18.6
ERROR 42703: column "gross" does not exist
3 │ WHERE gross > 100;
at line 3, column 7

two ways out. say the expression again, or give it its name one level down, in a subquery, so it's an ordinary column by the time the outer WHERE runs. same answer either way:

sqldb=shop
SELECT count(*) FROM products WHERE price * 1.2 > 100;
SELECT count(*) FROM (SELECT price * 1.2 AS gross FROM products) AS p WHERE gross > 100;
output, from postgres 18.6
#1 · SELECT 1
countint8
122
(1 row)
#2 · SELECT 1
countint8
122
(1 row)
predict the output
sql
SELECT category, name
FROM products
GROUP BY category;

the real error names the column and the rule:

sqldb=shop
SELECT category, name
FROM products
GROUP BY category;
output, from postgres 18.6
ERROR 42803: column "products.name" must appear in the GROUP BY clause or be used in an aggregate function
1 │ SELECT category, name
at line 1, column 18

one value per bucket, and it runs:

sqldb=shop
SELECT category, count(*) AS n, min(name) AS first_name
FROM products
GROUP BY category
ORDER BY category;
output, from postgres 18.6
SELECT 11
categorytextnint8first_nametext
audio21bamboo earbuds
bath27basic towel
books12bamboo cookbook
games14bamboo board game
garden15bamboo watering can
kitchen19bamboo saucepan
office26bamboo binder
outdoor22bamboo hammock
pets17bamboo chew toy
toys24basic marble run
null3large lantern
(11 rows)

the full order

the products query uses seven clauses. a SELECT can have a few more, and they all have a place on the line:

#clausewhat it doesyou'll feel it when
1WITHcomputes the named subqueriesyou name a subquery once and use it twice (CTEs)
2FROM, JOINbuilds one working table from every table nameda join multiplies rows before anyone else gets a say (fan-out)
3WHEREkeeps the rows where the condition is trueyou reach for an alias or an aggregate: neither exists yet
4GROUP BYturns rows into buckets, one per distinct keya selected column is neither grouped nor aggregated
5HAVINGkeeps the buckets where the condition is trueyou filter on count(*): WHERE can't, HAVING can
6window functionscompute across the surviving rows without merging themyou put row_number() in WHERE
7SELECTcomputes the output columns and names themaliases are born here
8DISTINCTdrops duplicate output rowsit compares whole output rows, computed columns included
9UNION, INTERSECT, EXCEPTcombines two resultsa final ORDER BY sorts the combined result, not one half
10ORDER BYsortsthe only clause that sees aliases (bare ones, see below)
11OFFSET, LIMIT, FETCH FIRSTcuts the result downLIMIT without ORDER BY gives you some rows, not the first ones
quick check
where can row_number() OVER (ORDER BY price DESC) not go?

WHERE is too early, and postgres says so by name:

sqldb=shop
SELECT name, price
FROM products
WHERE row_number() OVER (ORDER BY price DESC) <= 3;
output, from postgres 18.6
ERROR 42P20: window functions are not allowed in WHERE
3 │ WHERE row_number() OVER (ORDER BY price DESC) <= 3;
at line 3, column 7

the fix is the same move as before: compute it one level down, filter one level up.

sqldb=shop
SELECT name, price
FROM (
  SELECT name, price, row_number() OVER (ORDER BY price DESC, id) AS rank
  FROM products
) AS ranked
WHERE rank <= 3
ORDER BY rank;
output, from postgres 18.6
SELECT 3
nametextpricenumeric
spare yo-yo198.32
family board game197.54
cotton cookbook196.45
(3 rows)

the plan doesn't care

everything so far is the logical order: what the answer has to be. it says nothing about how postgres gets there. here's what it actually ran for the products query:

show =
actual rowsestimated rows
real output, postgres 18.6 (PGlite 0.5.12) · logical-order
the plan for the products query. rows flow up from the scan. toggle estimates against actual rows: the aggregate guessed 3 groups would survive HAVING, and 10 did.

read it bottom-up and it looks like the kitchen line. but count: four nodes for seven clauses. WHERE isn't a station of its own, it's a filter inside the scan (12 rows removed). HAVING is a filter inside the aggregate (1 group removed). SELECT's expressions are computed by the aggregate on its way out. and ORDER BY with LIMIT became one top-N heapsort, which only ever holds the best 3 rows instead of sorting all 10.

and the resemblance is luck. ask for the first three products by id, and the logical order says: take all 200, sort them, keep 3. the plan does nothing of the sort:

sqldb=shop
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, name, price FROM products ORDER BY id LIMIT 3;
output, from postgres 18.6
EXPLAIN
Limit (actual rows=3.00 loops=1) -> Index Scan using products_pkey on products (actual rows=3.00 loops=1) Index Searches: 1

no Sort node. the primary key's index already hands rows over in id order. and the scan produced 3 rows, not 200 (actual rows=3.00): LIMIT got its three and stopped asking for more.

a HAVING that doesn't need the groups gets moved too. postgres pushes it down into the scan, so those rows never reach the aggregate:

sqldb=shop
EXPLAIN (COSTS OFF)
SELECT category, count(*) AS n
FROM products
GROUP BY category
HAVING category IS NOT NULL
ORDER BY category;
output, from postgres 18.6
EXPLAIN
Sort Sort Key: category -> HashAggregate Group Key: category -> Seq Scan on products Filter: (category IS NOT NULL)

you wrote it in HAVING. it runs as the scan's Filter. (HAVING has more on the HAVING that should have been a WHERE.)

that's the deal. the logical order fixes the answer, and the planner can take any route it likes as long as the answer matches. reading EXPLAIN and the iterator model are about the route.

one level deeperGROUP BY an alias: the standard says no, postgres says yes

the SQL-92 standard lets GROUP BY use only input columns (the table FROM built) and ORDER BY only output columns (SELECT's names and positions). postgres extends both, so GROUP BY can take an alias or a position too, even though SELECT nominally runs after it:

sqldb=shop
SELECT left(category, 1) AS initial, count(*) AS n
FROM products
GROUP BY initial
ORDER BY initial;
output, from postgres 18.6
SELECT 8
initialtextnint8
a21
b39
g29
k19
o48
p17
t24
null3
(8 rows)

when a name could mean either, postgres falls back to the standard's reading, and the two clauses disagree on purpose: GROUP BY picks the input column, ORDER BY the output column. here category is the table's column in GROUP BY, so bath and books stay separate buckets that both print as b, and the alias in ORDER BY:

sqldb=shop
SELECT left(category, 1) AS category, count(*) AS n
FROM products
GROUP BY category
ORDER BY category, n;
output, from postgres 18.6
SELECT 11
categorytextnint8
a21
b12
b27
g14
g15
k19
o22
o26
p17
t24
null3
(11 rows)

11 buckets, not 8. and the two b rows come out 12 before 27: ORDER BY sorted on the letter, then on n. sorted on the real column, bath's 27 would have come first.

HAVING gets none of this. in postgres it never sees aliases:

sqldb=shop
SELECT category, count(*) AS n
FROM products
GROUP BY category
HAVING n >= 10;
output, from postgres 18.6
ERROR 42703: column "n" does not exist
4 │ HAVING n >= 10;
at line 4, column 8

mysql is looser. its manual lets HAVING refer to select-list aliases, as an extension to the standard, so a query that runs there can fail here.

one level deeperwhy SELECT comes first anyway

SQL started out as SEQUEL (Chamberlin and Boyce at IBM, 1974), meant to read like an english sentence: select this, from there, where that holds. you say what you want before where it comes from, so SELECT went first. the price is this whole chapter: the reading order and the running order disagree, and your editor can't suggest column names until you've typed FROM.

newer syntaxes put FROM first. duckdb accepts FROM products SELECT name, and PRQL writes every query as a pipeline that starts with from. same order as the kitchen line, written down the way it runs.

keylines

  • a query is written SELECT-first and runs FROM-first.
  • every clause takes a table and hands a table to the next.
  • WHERE filters rows before grouping. HAVING filters groups after.
  • aliases are born in SELECT, so only ORDER BY can see them, and only bare.
  • the planner can take any route, as long as the answer matches this order.