Logical Order of a Query
SQL is written in one order and run in another. Learn the run order and it explains most confusing errors, such as aliases in WHERE.
Written order is not run order
You write SELECT first, but the database does not run it first. It runs the clauses in a fixed logical order: FROM, then WHERE, then GROUP BY, then HAVING, then SELECT, then DISTINCT, then ORDER BY, and finally LIMIT and OFFSET.
Each step takes the table the previous step produced and passes a new table to the next one.
It explains the rules you just learned
Why can WHERE not use count(*)? Because groups appear two steps later. Why can HAVING use it? Because it runs right after grouping. Almost every "why can I not write this?" in SQL has its answer in this order.
Follow one query through the steps
SELECT team, count(*) AS n
FROM players
WHERE points IS NOT NULL
GROUP BY team
HAVING count(*) >= 2
ORDER BY n DESC;FROM gives 8 rows. WHERE removes Chen and Eli, leaving 6. GROUP BY makes 3 groups of 2. HAVING keeps groups with at least 2 rows, so all 3 stay. SELECT builds the rows (team, n). ORDER BY sorts them.
The name n is created at the SELECT step. That is why ORDER BY n works: it runs afterwards. And it is why WHERE n >= 0 does not work.
Step through a query
Press the steps one at a time and watch the table change. Then switch on Use n in WHERE and step past WHERE to see the error.
| nametext | teamtext | pointsinteger |
|---|---|---|
| Asha | Red | 31 |
| Ben | Blue | 17 |
| Chen | Red | NULL |
| Dara | Green | 24 |
| Eli | Blue | NULL |
| Fay | Red | 24 |
| Gus | Green | 40 |
| Hana | Blue | 17 |
FROM runs first: it picks the table and gives all 8 rows to the next step.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A query runs in this order: FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT.
- WHERE sees single rows, so it cannot use aggregates. HAVING runs after grouping, so it can.
- A name created in SELECT exists for ORDER BY, but not for WHERE or HAVING.
- When a query surprises you, check the table after each step to find where it went wrong.
Done with this concept?
Mark it complete to track your progress. No login needed.