Index Order By Limit Avoids Sort

A btree index serves ORDER BY with LIMIT: the scan stops after n rows in either direction, and only a mismatched sort column falls back to a full sort.

SqlData Fetching

Code

snippet
-- btree 索引按 (created_at) 有序存放:ORDER BY 加 LIMIT 可以直接
-- 沿索引正序读,读够 LIMIT 就停,不再对全表做排序
CREATE INDEX orders_created_at_idx ON orders (created_at);

SELECT id, total_cents, created_at
FROM orders
ORDER BY created_at
LIMIT 5;

-- 反方向查询同样命中:倒序扫描同一个索引即可(无需 DESC 索引)
SELECT id, total_cents, created_at
FROM orders
ORDER BY created_at DESC
LIMIT 5;

-- 边界:排序列换成 total_cents 后,索引顺序帮不上忙,
-- 计划器只能先排序再取前 N
SELECT id, total_cents, created_at
FROM orders
ORDER BY total_cents
LIMIT 5;

Inside the snippet

Several statements share this file — SELECT / CREATE, with orders among the objects involved.

Breaking the statements into their working parts: an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.

Using it

Run the statement against the orders table; the LIMIT keeps the probe cheap while you tune the predicates.

Key statements

SELECT id, total_cents, created_at
FROM orders
ORDER BY created_at DESC
LIMIT 5;
SELECT id, total_cents, created_at
FROM orders
ORDER BY total_cents
LIMIT 5;
SELECT id, total_cents, created_at
FROM orders
ORDER BY created_at
LIMIT 5;

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`orders` — referenced directly, no join needed.