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.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.
FAQ
- What are the relations in play here?
- `orders` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.