Top-N partial range processing (sort elimination)
A screen showing the 10 most recent orders. Instead of sorting the whole result and letting the app use the first part, TOP and index order stop at 10 rows.
SQL
Situation
The admin home screen shows the 10 most recent paid orders. The query fetches all paid orders newest first, and the application uses only the first 10 on screen.
Tables
| Table | Column | Type | Description |
|---|---|---|---|
orders | status | varchar(10) | PAID is about 140,000 rows |
orders | ord_dt | datetime2(0) | Order date and time |
| Index | Columns |
|---|---|
orders_pk (clustered) | ord_id |
orders_x2 | status, ord_dt, ord_id |
Recent paid orders
BEFORE · Full sort
-- Sort the whole result and send it down; the app uses only the first 10 rows
SELECT *
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC
Run it and check how many rows the Sort operator sorted.
Approach
1. Check whether the DB was told how many rows are needed
Even if the app uses only 10 rows, the DB produces the whole result unless the SQL says so.
2. Check whether the index already has the sort order
WHERE status = 'PAID' ORDER BY ord_dt DESC matches the order of reading orders_x2(status, ord_dt, …) backward.
3. Weigh the Key Lookup cost
Because of SELECT *, columns not in the index must be fetched with Key Lookups. For 140,000 rows a full read is cheaper than Lookups, but for 10 rows 10 Lookups are far cheaper.
Explanation
Full sort → TOP + reverse index order
AFTER · TOP
SELECT TOP (10) *
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC
Why it got faster
- Before reads 139,682 paid orders with a
Clustered Index Scan(Buffers about 13,200) and sorts them withSort. - After, under
Top, reads 10 rows oforders_x2with anIndex Seek(backward) from the end of thePAIDrange, fetches the remaining columns with 10 Key Lookups, and stops. Buffers about 23. There is noSort.
Why this is optimal
- One index seek and 10 Key Lookups are the minimum needed to produce the 10 rows on screen.
Key points
- Top-N stops at the first N rows only when a row limit (
TOP) and a sorted index are both present. - Even with the same index, the optimizer's choice (Scan + Sort ↔ Seek + Key Lookup) changes with the number of rows fetched.
- DB differences: Oracle uses
ROWNUMorFETCH FIRST, PostgreSQL usesLIMIT, and SQL Server usesTOPorOFFSET … FETCH.