Incremental Sort Plan Fallback

Use a leading-column index then sort the remainder: the plan shows an Incremental Sort node instead of a full Sort when the prefix is presorted.

SqlData Fetching

Code

snippet
-- 演示前置列索引让排序走增量路径(PostgreSQL 13+)
CREATE TABLE readings (
    sensor_id int,
    taken_at  timestamptz,
    value     numeric
);

CREATE INDEX idx_readings_sensor ON readings (sensor_id);

-- ORDER BY 以索引列为前缀:索引已给出 sensor_id 顺序,
-- planner 只需在每组内部对 taken_at 排序 → Incremental Sort 节点
EXPLAIN (COSTS OFF)
SELECT sensor_id, taken_at
FROM readings
ORDER BY sensor_id, taken_at;

-- 对照:ORDER BY 借不到索引前缀 → 全量 Sort 节点
EXPLAIN (COSTS OFF)
SELECT taken_at, value
FROM readings
ORDER BY taken_at;

DROP TABLE readings;

How the snippet works

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

In terms of clauses, the statements use: an ORDER BY that fixes the output order.

Applying it

The readings table is the working surface here.

Statements that matter

EXPLAIN (COSTS OFF)
SELECT sensor_id, taken_at
FROM readings
ORDER BY sensor_id, taken_at;
CREATE TABLE readings (
sensor_id int,
taken_at  timestamptz,
value     numeric
);
EXPLAIN (COSTS OFF)
SELECT taken_at, value
FROM readings
ORDER BY taken_at;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
The references are `readings`.