How a SELECT actually runs
You write a query top to bottom. The database does not read it that way, and almost every confusing SQL error comes from that gap.
This is the first lesson in the track because it is the one that makes the others make sense. Once you can recite the order, half the errors stop being mysterious and start being obvious.
The order
A SELECT is evaluated in this logical order:
FROMandJOIN— assemble the rowsWHERE— throw rows awayGROUP BY— collapse rows into groupsHAVING— throw groups awaySELECT— compute the output columnsDISTINCTORDER BY— sort what survivedLIMIT/OFFSET— take a slice
“Logical” is doing real work in that sentence. This is the order the meaning is defined in, not the order the engine executes in — a planner will happily push a filter down into a join or skip a sort it can read off an index. What the order guarantees is the answer, not the method.
What it immediately explains
You cannot use a SELECT alias in WHERE
SELECT name, salary * 12 AS annual
FROM employee
WHERE annual > 1000000;
WHERE runs at step 2 and SELECT at step 5. When WHERE is evaluated,
annual does not exist yet. Postgres says so plainly:
ERROR: column "annual" does not exist
Repeat the expression, or wrap the query:
SELECT name, salary * 12 AS annual
FROM employee
WHERE salary * 12 > 1000000;
But you can use one in ORDER BY
SELECT name, salary * 12 AS annual
FROM employee
ORDER BY annual DESC;
ORDER BY is step 7, after SELECT at step 5, so the alias exists by then.
This asymmetry looks arbitrary until you have the order in your head, at which
point it is the only thing it could be.
HAVING is not a second WHERE
WHERE filters rows, before grouping. HAVING filters groups, after.
SELECT department_id, count(*) AS headcount
FROM employee
WHERE salary > 60000
GROUP BY department_id
HAVING count(*) > 1;
The WHERE drops individual employees earning 60,000 or less. The HAVING
then drops whole departments that have fewer than two survivors. Swap them and
the query means something different; put an aggregate in WHERE and it is an
error, because at step 2 there are no groups to aggregate over.
LIMIT does not make a query cheap
SELECT name, salary
FROM employee
ORDER BY salary DESC
LIMIT 3;
LIMIT is step 8 — dead last, after the sort. To know which three rows are the
top three, the engine has to order the rows, and to order them it has to have
them. A LIMIT 10 over a ten-million-row scan is a ten-million-row scan that
then discards almost everything.
This is the single most common misconception about LIMIT, and it is the setup
for the indexes lesson later in the track: an index on salary can let the
engine walk rows in order and stop after three, which is what actually makes
the query cheap. LIMIT expresses what you want. The index is what makes it
fast.
Where NULL enters
Step 2 is also where three-valued logic starts to bite. WHERE keeps a row only
when the condition is true — not when it is unknown.
SELECT name, department_id
FROM employee
WHERE department_id <> 1;
Grace has no department. NULL <> 1 is not false, it is unknown, so her row is
not kept — and is not reported either. That is a whole lesson on its own, and it
is the next-but-two in this part.
Try it
Every example above runs against the same three tables — department,
employee and sale. Open the SQL playground and paste any
of them; the schema is already loaded.
The companion drill is
Rows blocking a unique index, which
turns on exactly the WHERE-before-HAVING split above.
Interview questions
1. Why can you reference a SELECT alias in ORDER BY but not in WHERE?
Because WHERE is evaluated before SELECT and ORDER BY after it. The alias
does not exist at step 2 and does exist at step 7.
2. What is the difference between WHERE and HAVING?
WHERE filters rows before grouping; HAVING filters groups after. An
aggregate can appear in HAVING and cannot appear in WHERE, because groups do
not exist yet when WHERE runs.
3. Does LIMIT 10 make a query ten times cheaper than LIMIT 100?
Usually not. LIMIT is applied last, so unless an index lets the engine produce
rows already in the required order and stop early, the full scan and sort happen
either way.
4. A query has WHERE status <> 'closed' and is missing rows you expect. What
would you check first?
Whether status is nullable. NULL <> 'closed' is unknown, not true, so those
rows are silently excluded. WHERE status IS DISTINCT FROM 'closed' or
WHERE status <> 'closed' OR status IS NULL includes them.
5. If the logical order is fixed, why do two queries that mean the same thing have different plans? Because the order defines the result, not the execution. The planner is free to reorder anything that cannot change the answer — pushing predicates into joins, choosing an index scan over a sort, collapsing a subquery — and it chooses using table statistics.
6. Where does DISTINCT run, and why does that matter with ORDER BY?
After SELECT and before ORDER BY. You can only order by something that
survived the projection, which is why SELECT DISTINCT name FROM employee ORDER
BY salary is an error: salary is not in the output.
Next
Inner and outer joins — step 1 of the order, where the rows come from in the first place.
If you are weighing a relational database against something else entirely, SQL vs NoSQL is the design-level version of that question.