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.

SqlCli Tooling

Code

snippet
-- 分区表上带 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

FAQ

Which tables appear in this script?
The references are `measurements`.