Top-N Heapsort With LIMIT
A small LIMIT keeps only the top rows in an in-memory heap, which EXPLAIN ANALYZE labels top-N heapsort, instead of fully sorting the table.
Code
-- ORDER BY + 小 LIMIT 的专用排序路径:只需在内存堆里留住前 N 行,
-- EXPLAIN ANALYZE 的 Sort Method 显示 top-N heapsort;去掉 LIMIT 就退回完整排序
SET work_mem = '64kB';
CREATE TEMP TABLE bids (
bid_id bigint GENERATED ALWAYS AS IDENTITY,
amount numeric NOT NULL
);
INSERT INTO bids (amount)
SELECT random() * 10000 FROM generate_series(1, 50000);
-- 前十名:堆里始终只放 10 行,排序内存压力与表大小无关
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF)
SELECT bid_id, amount FROM bids ORDER BY amount DESC LIMIT 10;
-- 同一查询去掉 LIMIT:必须物化全部行,数据超过 work_mem 时 external merge 落盘
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF)
SELECT bid_id, amount FROM bids ORDER BY amount DESC;How the snippet works
The file runs SELECT / INSERT / CREATE / EXPLAIN statements, touching bids and generate_series.
bids is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.
The pieces that do the work: an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
The file sets up its own scratch surface: it builds the session-local tables it works with (bids), so one full run against a throwaway database is enough.
Statements that matter
INSERT INTO bids (amount)
SELECT random() * 10000 FROM generate_series(1, 50000);
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF)
SELECT bid_id, amount FROM bids ORDER BY amount DESC LIMIT 10;
CREATE TEMP TABLE bids (
bid_id bigint GENERATED ALWAYS AS IDENTITY,
amount numeric NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which objects does the SQL touch?
- `bids`, `generate_series`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.