2. How SQL runs a query
You write a query top to bottom, starting with SELECT. But the
database doesn't run it in that order. Knowing the real order clears up
most early confusion — especially "why can't I use my alias here?"
The order you write vs. the order it runs
A fuller query has more parts:
SELECT title, rental_rate -- 5. pick columns to show
FROM film -- 1. start with this table
WHERE rental_rate > 2.99 -- 2. keep only rows that match
ORDER BY rental_rate DESC -- 6. sort the result
LIMIT 5; -- 7. keep only the first few
The database actually works through it like this:
- FROM — get the rows from the table.
- WHERE — throw away rows that don't match the condition.
- GROUP BY — bundle rows into groups (later module).
- HAVING — filter those groups (later module).
- SELECT — pick or compute the columns to return.
- ORDER BY — sort what's left.
- LIMIT — take just the top N rows.
So the machine grabs the data first and decides what columns to show almost last. That single fact explains a lot.
Why the order matters
Because WHERE runs before SELECT, a name you invent in SELECT (an
alias) doesn't exist yet when WHERE runs:
SELECT title, rental_rate * 100 AS price_cents
FROM film
WHERE rental_rate > 2.99 -- fine: rental_rate is a real column
ORDER BY price_cents; -- fine: ORDER BY runs AFTER SELECT, so the alias exists
ORDER BY can use price_cents because sorting happens after the
columns are computed. Trying to write WHERE price_cents > 299 would
fail — that alias isn't born yet. (You'd repeat the expression, or wrap
the query — both covered later.)
Try it
List the title and length of every film rated 'NC-17', sorted by
title in alphabetical order.
SELECT title, length
FROM film
WHERE rating = 'NC-17'
-- add sorting by title
SELECT title, length
FROM film
WHERE rating = 'NC-17'
ORDER BY title;
Keep the 7-step order in the back of your mind. Every clause you learn from here slots into one of those steps.