Sub topic 10
Where DISTINCT, ORDER BY, LIMIT, and OFFSET run in a query
This chapter assumes you can write a SELECT ... FROM ... WHERE query and sort with ORDER BY. It also assumes you know what DISTINCT and LIMIT do on their own. Here the question is when each clause runs. That order explains several errors and surprising results.
Written order versus logical order
You write a query starting with SELECT. The database does not run it in that order. SQL defines a logical order of evaluation, and the results must be the same as if the clauses ran in this sequence:
FROM(and joins) builds the set of input rows.WHEREdiscards rows that fail the condition.GROUP BYforms groups.HAVINGdiscards groups that fail the condition.SELECTcomputes the output expressions, including aggregates, window functions, and aliases.DISTINCTremoves duplicate output rows.ORDER BYsorts the remaining rows.OFFSETskips the first rows of the sorted result.LIMIT(orFETCH FIRST) keeps only the requested number of rows.
This is a logical model. The optimizer is free to reorder work, for example by reading rows in index order so it can skip a sort, or by stopping early once LIMIT is satisfied. It must still return what the logical order would return.
| Clause | Sees | Can use SELECT aliases? |
|---|---|---|
| `WHERE` | Individual input rows | No |
| `GROUP BY` | Rows that passed `WHERE` | Depends on the database |
| `HAVING` | Groups | Depends on the database |
| `ORDER BY` | Output rows after `DISTINCT` | Yes |
| `OFFSET` / `LIMIT` | Sorted output rows | Not applicable |
Consequence 1: WHERE cannot see SELECT aliases
WHERE runs before the SELECT list is computed, so an alias defined there does not exist yet.
SELECT order_id, total * 1.2 AS total_with_tax
FROM orders
WHERE total_with_tax > 100;PostgreSQL reports that the column total_with_tax does not exist. Repeat the expression instead:
SELECT order_id, total * 1.2 AS total_with_tax
FROM orders
WHERE total * 1.2 > 100
ORDER BY total_with_tax DESC;ORDER BY runs after SELECT, so it can use the alias. Some databases, such as MySQL and SQLite, are more lenient about aliases in other clauses. Do not rely on that if your queries need to move between systems.
Consequence 2: LIMIT counts rows after DISTINCT
DISTINCT runs before LIMIT. When you combine them, the limit counts unique rows, not input rows.
SELECT DISTINCT country
FROM customers
LIMIT 3;This returns three different countries, assuming at least three exist. If you leave out DISTINCT, the query returns the first three rows, and those may all contain the same country.
SELECT country
FROM customers
LIMIT 3;The database can stop reading input only when it has found three unique values. With a few distinct values spread over a large table, it may have to read a lot of rows before it gets there.
Consequence 3: ORDER BY sorts the deduplicated rows
Because DISTINCT comes before ORDER BY, the sort works on the unique output rows. This pattern from the plan shows the full chain:
SELECT DISTINCT country
FROM customers
ORDER BY country
LIMIT 5 OFFSET 5;The steps are:
- Read
customers. - Compute the
countrycolumn. - Remove duplicate countries.
- Sort the unique countries.
- Skip five.
- Return the next five.
The page you get is the second page of a list of unique, sorted countries. It is not the second page of customer rows.
ORDER BY with DISTINCT can only use what survives
After DISTINCT, each output row may stand for many input rows. A column that is not in the select list has no single value for that row. Consider this query:
SELECT DISTINCT country
FROM customers
ORDER BY city;A country such as Germany has many cities. Which city should decide where Germany goes in the order? PostgreSQL rejects the query with the message "for SELECT DISTINCT, ORDER BY expressions must appear in select list". Other systems may reject it as well, and some accept it but leave the order undefined.
You have two honest options. Add the column to the list and accept that DISTINCT now applies to both columns:
SELECT DISTINCT country, city
FROM customers
ORDER BY city;Or define what you mean with an aggregate:
SELECT country, MIN(city) AS first_city
FROM customers
GROUP BY country
ORDER BY first_city;The second query says explicitly that each country is placed by its alphabetically first city.
Consequence 4: aggregates run before LIMIT
Aggregate functions are computed in the SELECT step, so LIMIT cannot reduce the rows an aggregate reads. This query does not count five orders:
SELECT COUNT(*) AS order_count
FROM orders
LIMIT 5;It counts all orders and produces a single row. LIMIT 5 then keeps up to five rows, which is the one row you already have. To count only the five most recent orders, apply the limit in a subquery. The subquery's result becomes the input of the outer FROM:
SELECT COUNT(*) AS recent_count
FROM (
SELECT order_id
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 5
) AS recent;The same technique works whenever you want to limit rows before some other step, such as a join or an aggregate. Wrap the limited query in a subquery or a common table expression.
Consequence 5: OFFSET and LIMIT depend on the sort
OFFSET and LIMIT work on whatever order the rows have at that point. If there is no ORDER BY, or if it has ties, the database may order tied rows differently from one run to the next. Paging then can repeat a row on two pages or skip it entirely. Add a unique tie-breaker, such as the primary key, as the last sort key:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10 OFFSET 20;Here order_id makes the order total, so rows 21 to 30 are the same each time, provided the data does not change between requests.
Note the written order too. LIMIT and OFFSET are always written after ORDER BY, even though people often say "limit, then offset". In the logical order the offset is applied first, then the limit. LIMIT 10 OFFSET 20 means "skip 20, then take 10". The order you type LIMIT and OFFSET in does not change this in dialects that accept both orders.
Window functions and the same rule
Window functions such as ROW_NUMBER() are computed in the SELECT step. That puts them after WHERE and HAVING, and before DISTINCT, ORDER BY, and LIMIT. Two results follow:
- You cannot filter on a window function in
WHERE. Put the query in a subquery and filter in the outer query. - A window function value can differ between rows that
DISTINCTwould otherwise treat as duplicates. AddingROW_NUMBER()to aSELECT DISTINCTmakes every row unique, so nothing is removed.
SELECT DISTINCT country, ROW_NUMBER() OVER (ORDER BY country) AS rn
FROM customers;This query removes nothing, because rn is different on every row.
A debugging checklist
When a query returns something unexpected, walk the logical order from the top:
- Does
WHEREuse an alias or aggregate that does not exist yet? - Does
DISTINCTapply to more columns than you meant, for example because you added an ID or a window function? - Does
ORDER BYuse a column thatDISTINCThas already removed? - Is the sort fully determined, with a unique last key?
- Is
LIMITapplied to the rows you intended, or does it need to move into a subquery?
Exercise
A teammate writes SELECT DISTINCT country FROM customers ORDER BY city LIMIT 5; and the database returns an error. Explain, using the logical order of evaluation, why it fails, and give one rewrite that returns five countries.
Show answer
DISTINCT runs before ORDER BY, so after it only unique country values remain, and each stands for many customers in many cities. city is no longer a single value per row, so the database cannot sort on it. One rewrite is SELECT country, MIN(city) AS first_city FROM customers GROUP BY country ORDER BY first_city LIMIT 5;, which defines the sort value as each country's alphabetically first city. Another is SELECT DISTINCT country FROM customers ORDER BY country LIMIT 5;, which sorts on the column you actually return.
Exercise
You want the average total of the 100 most recent orders. A colleague writes SELECT AVG(total) FROM orders ORDER BY order_date DESC LIMIT 100;. What does it return, and how do you fix it?
Show answer
It returns the average of all orders, as one row. AVG runs in the SELECT step, before LIMIT, so LIMIT 100 has no effect on the one result row. Limit in a subquery: SELECT AVG(total) AS avg_total FROM (SELECT total FROM orders ORDER BY order_date DESC, order_id DESC LIMIT 100) AS recent;.