Sub topic 10
Where DISTINCT, ORDER BY, LIMIT, and OFFSET Run in a Query
Assume you know basic SELECT, FROM, WHERE, and ORDER BY syntax. You should also understand that a table contains rows and columns. This chapter focuses on the logical order in which SQL forms a result, not necessarily the physical steps chosen by the database optimizer.
The logical order of evaluation
Although a query is written starting with SELECT, SQL generally evaluates its clauses in this logical order:
FROMchooses the source rows.WHEREfilters those rows.SELECTproduces the requested expressions.DISTINCTremoves duplicate result rows.ORDER BYsorts the remaining rows.OFFSETskips rows from that sorted result.LIMITreturns only the requested number of rows.
Some references place projection and duplicate removal together, because the database must know the selected values before it can compare rows for duplication. The important idea is that DISTINCT applies to the result columns, while ORDER BY, OFFSET, and LIMIT operate on the resulting set.
The database optimizer may physically use a different plan. It can use an index, sort earlier, or stop reading after finding enough rows. These optimizations must preserve the same result as the logical order.
DISTINCT before ORDER BY and LIMIT
Consider a customers table with repeated countries:
SELECT DISTINCT country
FROM customers
ORDER BY country
LIMIT 5 OFFSET 5;The logical result is:
- Read rows from
customers. - Select the
countryvalue. - Remove repeated country values.
- Sort the unique countries alphabetically.
- Skip the first five countries.
- Return the next five.
If LIMIT ran before DISTINCT, repeated values could consume the limit and produce fewer than five unique countries. The query instead limits the de-duplicated, sorted result.
DISTINCT applies to the complete selected row. With multiple columns, two rows are duplicates only when every selected value matches.
SELECT DISTINCT country, city
FROM customers
ORDER BY country, city
LIMIT 10;This returns unique (country, city) pairs. The database does not remove duplicate countries while ignoring cities.
ORDER BY makes the final rows predictable
Without ORDER BY, SQL does not promise a particular row order. A query such as this one may return different rows after an index change, data update, or database restart:
SELECT order_id, order_date, total
FROM orders
LIMIT 5;For a stable result, sort before applying LIMIT or OFFSET:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 5 OFFSET 10;The order_id tie-breaker matters. If several orders have the same order_date, sorting only by date leaves their relative order unspecified. Adding a column that is unique, or sufficiently unique, makes page boundaries deterministic.
| Clause | Logical purpose | Result |
|---|---|---|
| `DISTINCT` | Removes repeated selected rows | One row per unique result |
| `ORDER BY` | Establishes row order | Sorted result |
| `OFFSET` | Skips sorted rows | Starts later in the result |
| `LIMIT` | Restricts returned rows | Maximum number of rows |
A common error
Do not assume that LIMIT identifies the same records on every execution unless the ordering is deterministic. For example, ORDER BY order_date DESC can still produce unstable pages when dates tie. Use a secondary key:
SELECT DISTINCT country
FROM customers
ORDER BY country
LIMIT 10 OFFSET 20;Here, country is both the selected value and the complete sort key, so each distinct result has a defined position. In a query selecting several columns, include a consistent tie-breaker in ORDER BY.
Exercise
In what order are DISTINCT, ORDER BY, OFFSET, and LIMIT logically applied?
Show answer
DISTINCT removes duplicate selected rows, ORDER BY sorts the remaining rows, OFFSET skips rows in that order, and LIMIT returns the remaining requested maximum.