WindowAgg Plan Sort And Index
Read EXPLAIN for window queries: the Sort node feeding WindowAgg, how a matching index removes the Sort, and why distinct windows stack separate nodes.
Code
CREATE TABLE readings (
station text NOT NULL,
taken_at timestamptz NOT NULL,
value numeric NOT NULL
);
INSERT INTO readings VALUES
('oslo', '2026-01-05 08:00+00', 4),
('oslo', '2026-01-05 14:00+00', 9),
('tokyo', '2026-01-05 08:00+00', 11);
-- ① 无索引:数据先按分区+排序键排好(Sort 节点),再交给 WindowAgg 逐帧计算
EXPLAIN (COSTS OFF)
SELECT station, taken_at,
AVG(value) OVER (PARTITION BY station ORDER BY taken_at) AS rolling_avg
FROM readings;
-- ② 匹配索引提供 (station, taken_at) 顺序:计划里的 Sort 消失
CREATE INDEX readings_station_taken_idx ON readings (station, taken_at);
EXPLAIN (COSTS OFF)
SELECT station, taken_at,
AVG(value) OVER (PARTITION BY station ORDER BY taken_at) AS rolling_avg
FROM readings;
-- ③ 第二个窗口排序键不同(全局 taken_at):需要再排一次、再叠一层 WindowAgg
EXPLAIN (COSTS OFF)
SELECT station,
AVG(value) OVER (PARTITION BY station ORDER BY taken_at) AS per_station,
MAX(value) OVER (ORDER BY taken_at) AS global_max
FROM readings;What the code does
SELECT / INSERT / CREATE / EXPLAIN statements share the script, touching readings.
Mechanically, the statements are built from: AVG, MAX aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
Watch out for
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Applying it
The readings table is the working surface here.
Statements that matter
EXPLAIN (COSTS OFF)
SELECT station,
AVG(value) OVER (PARTITION BY station ORDER BY taken_at) AS per_station,
MAX(value) OVER (ORDER BY taken_at) AS global_max
FROM readings;
EXPLAIN (COSTS OFF)
SELECT station, taken_at,
AVG(value) OVER (PARTITION BY station ORDER BY taken_at) AS rolling_avg
FROM readings;
INSERT INTO readings VALUES
('oslo', '2026-01-05 08:00+00', 4),
('oslo', '2026-01-05 14:00+00', 9),
('tokyo', '2026-01-05 08:00+00', 11);
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 objects does the SQL touch?
- `readings`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.