Merge Append Plan Over Partitions
Read EXPLAIN on a partitioned ORDER BY query: Merge Append merges each partition pre-sorted index stream, so LIMIT can stop early without a global sort.
Code
-- 分区表上带 ORDER BY 的查询:计划用 Merge Append 按序合并各分区,
-- 每个分区自己的索引提供有序输入,父表无需全局排序
CREATE TABLE measurements (
taken_at timestamptz NOT NULL,
value numeric NOT NULL
) PARTITION BY RANGE (taken_at);
CREATE TABLE measurements_2026 PARTITION OF measurements
FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');
CREATE TABLE measurements_2025 PARTITION OF measurements
FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
CREATE INDEX ON measurements_2026 (taken_at DESC);
CREATE INDEX ON measurements_2025 (taken_at DESC);
EXPLAIN (COSTS OFF)
SELECT * FROM measurements ORDER BY taken_at DESC LIMIT 10;
-- 计划顶层是 Merge Append:每个分区用各自的索引提供有序输入,
-- 合并后整体仍有序,LIMIT 得以提前终止,不会对全表做一次大排序How it works
What runs here is SELECT / CREATE / EXPLAIN — measurements are 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; NOT NULL qualifiers on the required columns.
Using it
Run the statement against the measurements table; the LIMIT keeps the probe cheap while you tune the predicates.
Key statements
CREATE TABLE measurements (
taken_at timestamptz NOT NULL,
value numeric NOT NULL
) PARTITION BY RANGE (taken_at);
CREATE TABLE measurements_2026 PARTITION OF measurements
FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');
CREATE TABLE measurements_2025 PARTITION OF measurements
FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
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.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.
FAQ
- Which tables appear in this script?
- The references are `measurements`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.