Read the clauses in the order they run, and say what one row is after each
The second step reads the query itself, but not from the top down.
Which runs first: SELECT, WHERE or FROM?
Here's a generated answer to the March question:
SELECT c.city, COUNT(*) AS customers
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.placed_at >= '2026-03-01' AND o.placed_at < '2026-04-01'
GROUP BY c.city
ORDER BY c.city;orders o and customers c give each table a short alias, the same as writing orders AS o. So c.city is the city column of customers.
The database doesn't run the clauses in the order they're written. Here's the order it runs them in, and what one row is after each:
| As written | Runs | One row after it is |
|---|---|---|
SELECT c.city, COUNT(*) | 4 | a city, with its count |
FROM orders o | 1 | an order |
JOIN customers c ON ... | 1 | an order, with its city |
WHERE placed_at in March | 2 | a March order |
GROUP BY c.city | 3 | a group: one city's orders |
ORDER BY c.city | 5 | the same rows, sorted |
Read down the run order, 1 to 5, and the bug shows at step 4. COUNT(*) counts the rows in each group, and a row is an order. So this query counts March orders per city, and a customer with two orders counts twice. The question counts customers.
That answers both halves of the round, the logic and what's wrong, and you found it by reading. A fixture proves it.
The same order holds for every query:
FROMand eachJOIN, left to right: the rows you start with.WHERE: the rows that survive. A row stays only if the condition is true. False and NULL both drop it.GROUP BY: one row per group.HAVINGthen drops whole groups.SELECT: the aggregates over each group, then window functions over the grouped rows.DISTINCT,ORDER BY,LIMIT.
Window functions run near the end. That's why the SQL window functions lesson numbers rows in a CTE and filters outside it: a WHERE runs before any window exists.
In the editor, write in_run_order(clauses): the run order, as a sort.
- 1
Write
in_run_order(clauses): the clause names sorted into the order the database runs them. - 2
The order is FROM, then WHERE, GROUP BY, HAVING, SELECT, and ORDER BY last.
Run your code to check it. Output shows here.