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.

SqlCli Tooling

Code

snippet
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-level WHERE will 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

FAQ

Which objects does the SQL touch?
`readings`.