Sub topic 15
Why clause order matters: how a query is evaluated
This chapter assumes you can already write basic SELECT, WHERE, and ORDER BY statements, know what a column alias is, and have a table of employees to practice on. Examples run on PostgreSQL, MySQL, and SQLite unless noted.
Written order versus evaluated order
You write a query starting with SELECT. The database does not start there. It follows a fixed logical sequence. This sequence is a conceptual model. The optimizer may physically reorder work for speed, but the result must match what the logical order would produce.
For the clauses covered in this tutorial, the logical order is:
FROMfinds the source table and produces every row.WHEREdiscards rows that do not satisfy the condition.SELECTcomputes the output expressions and assigns aliases.DISTINCTthen removes duplicate output rows.ORDER BYsorts the remaining rows.LIMITorFETCH FIRSTkeeps only the first rows of the sorted result.
Other clauses such as GROUP BY, HAVING, and joins fit into this sequence too. GROUP BY and HAVING come after WHERE and before SELECT. Later chapters cover them. The key point here is that WHERE runs before SELECT, and ORDER BY runs after it.
Why aliases work in ORDER BY but not in WHERE
An alias is created during the SELECT step. Any clause that runs before that step cannot see it. Any clause that runs after can.
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE salary > 40000
ORDER BY annual_salary DESC;Here WHERE uses the original column salary, which exists as soon as FROM reads the table. ORDER BY uses annual_salary, which SELECT has already created.
Now try filtering on the alias:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 480000;PostgreSQL and standard-compliant databases reject this with an error such as column "annual_salary" does not exist. The fix is to repeat the expression:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE salary * 12 > 480000;Or, when the condition can be rewritten in terms of the original column, use that:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE salary > 40000;ORDER BY can also use things not in the SELECT list
Because ORDER BY runs after FROM has made all columns available, you can sort by a column you did not select:
SELECT first_name, last_name
FROM employees
ORDER BY hire_date;This works in all three databases. There is one exception. With SELECT DISTINCT, most databases require the ORDER BY expressions to appear in the select list, because sorting by a hidden column would make the meaning of "distinct" ambiguous. PostgreSQL reports for SELECT DISTINCT, ORDER BY expressions must appear in select list.
ORDER BY also accepts the position of a column in the select list:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
ORDER BY 2 DESC;This sorts by the second output column. It is compact for quick exploration, but it breaks silently if someone reorders the select list. Prefer names or aliases in code that will be maintained.
Aliases and name conflicts in ORDER BY
When an alias has the same name as a real column, ORDER BY has to choose which one you mean. The standard rule is that an output alias is matched first. The details differ across databases when the name appears inside an expression.
SELECT first_name, -salary AS salary
FROM employees
ORDER BY salary;In PostgreSQL, a bare name in ORDER BY refers to the output column, so this sorts by the negated value. In an expression such as ORDER BY salary + 0, PostgreSQL treats salary as the input column instead. To avoid surprises, give aliases names that differ from the source columns.
LIMIT comes last, so ORDER BY must come first
Row limiting is applied to the already sorted rows. That is why top-N queries pair ORDER BY with LIMIT:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;Without ORDER BY, the database returns any five rows, and which five can change between runs. Table rows have no guaranteed order. The sort is what gives the limit a meaning.
The same query in standard SQL, supported by PostgreSQL and by databases such as Oracle (12c and later), SQL Server (with OFFSET), and DB2, is:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;SQL Server's TOP 5 appears right after SELECT, but it is still applied after sorting.
Ties matter too. If the fifth and sixth employees have the same salary, LIMIT 5 returns only one of them, chosen arbitrarily. To make the result repeatable, add a tiebreaker column:
SELECT first_name, salary
FROM employees
ORDER BY salary DESC, employee_id
LIMIT 5;PostgreSQL and standard SQL also offer FETCH FIRST 5 ROWS WITH TIES, which includes all rows tied with the last one.
Predicting results with the order
You can use the logical order to answer questions about a query before running it.
| Question | Answer | Reason |
|---|---|---|
| Can `WHERE` use an alias defined in `SELECT`? | No | `WHERE` runs before `SELECT` |
| Can `ORDER BY` use that alias? | Yes | `ORDER BY` runs after `SELECT` |
| Does `DISTINCT` see rows that `WHERE` removed? | No | `WHERE` runs first |
| Is `LIMIT` applied before sorting? | No | Sorting finishes first |
| Can `ORDER BY` use a column not selected? | Yes, except with `DISTINCT` | The source columns are still available |
Consider this query:
SELECT DISTINCT department
FROM employees
WHERE salary > 50000
ORDER BY department
LIMIT 3;Step by step: FROM reads all employees. WHERE keeps those earning more than 50000. SELECT keeps only department, and DISTINCT collapses repeated departments. ORDER BY sorts the unique names. LIMIT returns the first three. Departments in which nobody earns above 50000 never appear, because their rows were gone before DISTINCT ran.
Common errors
- Using an alias in
WHERE. The error says the column does not exist. Repeat the expression or filter on the source column. - Assuming a stable order without
ORDER BY. Results may look sorted by insertion order during testing and change later with new data, indexes, or a different query plan. - Writing clauses in the wrong written order. The syntax is fixed:
SELECT,FROM,WHERE,ORDER BY, then the limit. PuttingORDER BYbeforeWHEREis a syntax error. - Using
LIMITwithout a tiebreaker. Ties lead to results that differ between runs. - Sorting by position in shared code. Numbers in
ORDER BYbreak when the select list changes. - Combining
DISTINCTwithORDER BYon a hidden column. Add the column to the select list or removeDISTINCT.
Practice
Exercise
A colleague writes SELECT first_name, salary * 12 AS annual_salary FROM employees WHERE annual_salary > 600000 ORDER BY annual_salary; and gets an error. Explain why, and write a corrected query.
Show answer
WHERE is evaluated before SELECT, so the alias annual_salary does not exist yet when the condition is checked. Repeat the expression in WHERE: SELECT first_name, salary * 12 AS annual_salary FROM employees WHERE salary * 12 > 600000 ORDER BY annual_salary;. The ORDER BY can keep the alias because it runs after SELECT. Filtering on salary > 50000 is equivalent and simpler.
Exercise
A query returns the three highest-paid employees, but on some runs two employees with the same salary swap places at the cutoff. What is the cause and the fix?
Show answer
Several employees are tied on salary, and ORDER BY salary DESC does not say which tied row comes first, so LIMIT 3 picks among them arbitrarily. Add a unique tiebreaker column, for example ORDER BY salary DESC, employee_id LIMIT 3. Alternatively use FETCH FIRST 3 ROWS WITH TIES where supported, to return every tied row.
Exercise
Give the order in which these clauses are logically evaluated: ORDER BY, FROM, LIMIT, SELECT, WHERE.
Show answer
FROM, WHERE, SELECT, ORDER BY, LIMIT.