Sub topic 7
Why LIMIT needs ORDER BY
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query, sort with ORDER BY, and that you know a table is made of rows and columns. It also assumes you have met LIMIT as a way to cap the number of returned rows. Here you will learn why LIMIT without ORDER BY gives no reliable answer, how to make results deterministic, and which mistakes come up most often.
LIMIT trims, it does not choose
LIMIT n tells the database to stop after n rows. It says nothing about which n rows. That choice depends on the order in which rows reach the LIMIT step.
A relational table is an unordered set of rows. The database does not promise any particular order unless you ask for one. Without ORDER BY, the order is whatever the execution plan happens to produce.
SELECT order_id, order_date, total
FROM orders
LIMIT 5;This query is valid and will run. It returns five rows. Which five is not defined by the SQL language.
What decides the order when you do not ask for one
The order of unsorted results comes from the physical work the database does. Several things can change it:
- The access path. A full table scan may return rows in storage order, while an index scan returns them in index order.
- Updates and deletes. Changed rows may move, and freed space may be reused by new rows.
- Parallel execution. Several workers read parts of the table, and the order they finish in can vary between runs.
- Caching and concurrent scans. Some engines let a new scan join one already in progress, so it starts in the middle of the table.
- Statistics and plan changes. After
ANALYZEor a data load, the optimizer may pick a different plan for the same query.
On a small test table, the same query often returns the same rows every time. That makes the problem easy to miss. The bug appears later, with more data, a new index, or a database upgrade.
Making the result deterministic
A result is deterministic when the same query on the same data always returns the same rows in the same order. To get that, add an ORDER BY that ranks every row in a single, unambiguous position.
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC
LIMIT 5;This is better, but it can still be ambiguous. If several orders share the same order_date, the database may order them differently from one run to the next. When the fifth and sixth rows have the same date, either could be returned.
Add a tie-breaker
A tie-breaker is an extra sort column that separates rows with equal values in the earlier columns. A primary key or other unique column is the usual choice, because no two rows share it.
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 5;Now the sort key (order_date, order_id) is unique for every row. Each row has exactly one position, so the five most recent orders are always the same five rows. This is the pattern to use whenever you combine ORDER BY with LIMIT.
A worked example with ties
Suppose orders holds these rows:
| order_id | order_date | total |
|---|---|---|
| 101 | 2024-03-15 | 40.00 |
| 102 | 2024-03-15 | 15.50 |
| 103 | 2024-03-15 | 99.99 |
| 104 | 2024-03-14 | 20.00 |
Run ORDER BY order_date DESC LIMIT 2. The three rows from March 15 tie for first place, and only two fit. The database may return 101 and 102, or 103 and 101, or any other pair. All are valid answers to the query as written.
Now run ORDER BY order_date DESC, order_id DESC LIMIT 2. The sorted order is 103, 102, 101, 104. The result is always 103 and 102.
ORDER BY direction matters for "top" and "latest"
LIMIT takes rows from the start of the sorted result. To get the newest rows, sort descending. To get the smallest values, sort ascending.
-- Three cheapest orders, ties broken by the lower order_id
SELECT order_id, total
FROM orders
ORDER BY total ASC, order_id ASC
LIMIT 3;A common error is sorting ascending when you want the latest rows. You then get the oldest rows, and the query still runs without any error.
Ties at the boundary: what LIMIT cannot do
Even with a tie-breaker, LIMIT cuts at an exact count. If you want "the top 3 totals, including everyone tied for third", LIMIT 3 is the wrong tool. It will drop some tied rows, and the tie-breaker decides which.
Standard SQL offers FETCH FIRST n ROWS WITH TIES for this case, in databases that support it, such as PostgreSQL 13+ and Oracle 12c+. A window function such as RANK() can also do it. Both are outside this chapter, but you should know that a plain LIMIT always returns at most n rows.
Common errors
- No ORDER BY at all. The result is arbitrary. This is acceptable only when you truly do not care which rows come back, for example when peeking at a table's shape.
- ORDER BY on a non-unique column only. The result is mostly stable but can break at ties. Add the primary key as the last sort column.
- Different ORDER BY in each query of a paging sequence. If page 1 and page 2 sort differently, rows can repeat or vanish between pages. Keep the sort identical across pages.
- Sorting by an expression that returns NULL. Where
NULLvalues sort is not the same in every database. PostgreSQL and Oracle put them last in ascending order, while MySQL and SQLite put them first. AddNULLS FIRSTorNULLS LASTwhere supported, or filter the NULLs out. - Trusting a subquery's order. An
ORDER BYinside a subquery or view does not guarantee the order of the outer query. Put theORDER BYin the outermost query that has theLIMIT. - Relying on insertion order. Primary keys that auto-increment usually look like insertion order, but the database does not guarantee a result in that order unless you sort by the key.
Checking that your sort key is unique
Before relying on a tie-breaker, confirm that the combination of columns is truly unique. This query finds duplicates in a sort key. If it returns any rows, the key is not unique.
SELECT order_date, order_id, COUNT(*) AS row_count
FROM orders
GROUP BY order_date, order_id
HAVING COUNT(*) > 1;When order_id is a primary key, this query returns nothing, because a primary key is unique by definition. If your tie-breaker is not backed by a primary key or unique constraint, you have no guarantee.
Cost of sorting
ORDER BY has a price. To return the first rows in sorted order, the database must either sort the data or read it through an index that already has that order. A matching index lets the engine read the first few entries and stop. Without one, the engine may need to sort the whole set, or keep a running list of the best n rows, which is cheaper than a full sort but still reads every row.
For frequent "latest N" queries, an index on the sort columns in the same order and direction helps:
CREATE INDEX idx_orders_date_id
ON orders (order_date DESC, order_id DESC);Some engines can scan a regular ascending index backward, so the explicit DESC is not always required. Check your database's plan output with EXPLAIN to see whether it sorts or reads the index directly.
Summary of the rule
LIMITwithoutORDER BYreturns arbitrary rows.ORDER BYon a non-unique key returns a stable set only when no ties cross the cut point.ORDER BYwith a unique tie-breaker always returns the same rows in the same order.
Exercise
The query SELECT order_id, total FROM orders ORDER BY total DESC LIMIT 10; is run twice, and two runs return slightly different lists even though no data changed. What is the likely cause, and how do you fix it?
Show answer
Several orders probably share the same total at the cut-off point, so the database may order the tied rows differently between runs and LIMIT cuts through the tie. Add a unique tie-breaker, for example ORDER BY total DESC, order_id DESC, so every row has a single fixed position.
Exercise
A developer puts ORDER BY order_date inside a subquery and applies LIMIT 10 in the outer query, which has no ORDER BY. Why is the result unreliable, and where should the ORDER BY go?
Show answer
The order of a subquery's rows is not guaranteed to carry through to the outer query, so the outer LIMIT takes ten arbitrary rows. Put the ORDER BY (with a tie-breaker) in the same outer query as the LIMIT.