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).
- FROM200 × 9fetch the ingredients200 × 9
- WHERE188 × 912 rows outbin the bad ones188 × 912 rows out
- GROUP BY11 groupssort into bowls11 groups
- HAVING10 groups1 group outtoss the small bowls10 groups1 group out
- SELECT10 × 3aliases bornplate up, name the dishes10 × 3aliases born
- ORDER BY10 × 3by avg_priceline the plates up10 × 3by avg_price
- LIMIT3 × 37 rows outserve three3 × 37 rows 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.
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;| categorytext | nint8 | avg_pricenumeric |
|---|---|---|
| audio | 20 | 123.34 |
| pets | 16 | 117.64 |
| bath | 25 | 106.35 |
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.
- 1SELECT category, count(*) AS n, round(avg(price), 2) AS avg_price
- 2FROM products
- 3WHERE NOT discontinued
- 4GROUP BY category
- 5HAVING count(*) >= 10
- 6ORDER BY avg_price DESC
- 7LIMIT 3;
| idint4 | categorytext | pricenumeric | discontinuedbool | nametext |
|---|---|---|---|---|
| 8 | pets | 89.00 | t | cat tree |
| 17 | kitchen | 21.55 | t | spare grater |
| 34 | games | 148.19 | t | retro go board |
| 51 | bath | 153.30 | t | smart shower caddy |
| 68 | kitchen | 194.97 | t | bamboo saucepan |
| 85 | office | 71.44 | t | travel desk lamp |
| 102 | kitchen | 128.13 | t | folding kettle |
| 119 | bath | 28.65 | t | linen bath mat |
| 136 | kitchen | 129.18 | t | heavy whisk |
| 153 | office | 23.74 | t | bamboo stapler |
| 170 | outdoor | 77.67 | t | deluxe water bottle |
| 187 | audio | 49.70 | t | linen earbuds |
| 1 | kitchen | 49.00 | f | chef's knife |
| 2 | kitchen | 39.50 | f | cast iron pan |
| … 186 more | ||||
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
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.
SELECT name, price * 1.2 AS gross
FROM products
WHERE gross > 100;here it is failing for real:
SELECT name, price * 1.2 AS gross
FROM products
WHERE gross > 100;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:
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;| countint8 |
|---|
| 122 |
| countint8 |
|---|
| 122 |
SELECT category, name
FROM products
GROUP BY category;the real error names the column and the rule:
SELECT category, name
FROM products
GROUP BY category;one value per bucket, and it runs:
SELECT category, count(*) AS n, min(name) AS first_name
FROM products
GROUP BY category
ORDER BY category;| categorytext | nint8 | first_nametext |
|---|---|---|
| audio | 21 | bamboo earbuds |
| bath | 27 | basic towel |
| books | 12 | bamboo cookbook |
| games | 14 | bamboo board game |
| garden | 15 | bamboo watering can |
| kitchen | 19 | bamboo saucepan |
| office | 26 | bamboo binder |
| outdoor | 22 | bamboo hammock |
| pets | 17 | bamboo chew toy |
| toys | 24 | basic marble run |
| null | 3 | large lantern |
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:
| # | clause | what it does | you'll feel it when |
|---|---|---|---|
| 1 | WITH | computes the named subqueries | you name a subquery once and use it twice (CTEs) |
| 2 | FROM, JOIN | builds one working table from every table named | a join multiplies rows before anyone else gets a say (fan-out) |
| 3 | WHERE | keeps the rows where the condition is true | you reach for an alias or an aggregate: neither exists yet |
| 4 | GROUP BY | turns rows into buckets, one per distinct key | a selected column is neither grouped nor aggregated |
| 5 | HAVING | keeps the buckets where the condition is true | you filter on count(*): WHERE can't, HAVING can |
| 6 | window functions | compute across the surviving rows without merging them | you put row_number() in WHERE |
| 7 | SELECT | computes the output columns and names them | aliases are born here |
| 8 | DISTINCT | drops duplicate output rows | it compares whole output rows, computed columns included |
| 9 | UNION, INTERSECT, EXCEPT | combines two results | a final ORDER BY sorts the combined result, not one half |
| 10 | ORDER BY | sorts | the only clause that sees aliases (bare ones, see below) |
| 11 | OFFSET, LIMIT, FETCH FIRST | cuts the result down | LIMIT without ORDER BY gives you some rows, not the first ones |
row_number() OVER (ORDER BY price DESC) not go?WHERE is too early, and postgres says so by name:
SELECT name, price
FROM products
WHERE row_number() OVER (ORDER BY price DESC) <= 3;the fix is the same move as before: compute it one level down, filter one level up.
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;| nametext | pricenumeric |
|---|---|
| spare yo-yo | 198.32 |
| family board game | 197.54 |
| cotton cookbook | 196.45 |
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:
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:
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, name, price FROM products ORDER BY id LIMIT 3;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:
EXPLAIN (COSTS OFF)
SELECT category, count(*) AS n
FROM products
GROUP BY category
HAVING category IS NOT NULL
ORDER BY category;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:
SELECT left(category, 1) AS initial, count(*) AS n
FROM products
GROUP BY initial
ORDER BY initial;| initialtext | nint8 |
|---|---|
| a | 21 |
| b | 39 |
| g | 29 |
| k | 19 |
| o | 48 |
| p | 17 |
| t | 24 |
| null | 3 |
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:
SELECT left(category, 1) AS category, count(*) AS n
FROM products
GROUP BY category
ORDER BY category, n;| categorytext | nint8 |
|---|---|
| a | 21 |
| b | 12 |
| b | 27 |
| g | 14 |
| g | 15 |
| k | 19 |
| o | 22 |
| o | 26 |
| p | 17 |
| t | 24 |
| null | 3 |
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:
SELECT category, count(*) AS n
FROM products
GROUP BY category
HAVING n >= 10;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.