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.
Code
-- 演示前置列索引让排序走增量路径(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
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.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.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.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- Which tables or CTEs does it reference?
- The references are `readings`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.