Ranking Functions Ignore The Frame
rank, row_number, lag, and ntile ignore the frame clause entirely, while aggregates and first_value honor it — same frames, different results.
Code
-- ranking functions ignore the frame entirely;
-- aggregates and first_value honor it
CREATE TEMP TABLE readings (
taken_at time NOT NULL,
value int NOT NULL
);
INSERT INTO readings VALUES
('09:00', 10), ('09:05', 20), ('09:10', 30), ('09:15', 40);
SELECT
taken_at,
value,
-- 两种 frame 下 rank 完全相同:排名函数不看帧
rank() OVER (ORDER BY taken_at) AS rank_default,
rank() OVER (ORDER BY taken_at ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS rank_row_frame,
-- 聚合严格按 frame 算:默认帧含全部前序行,ROWS 帧只看上一行
sum(value) OVER (ORDER BY taken_at) AS sum_default,
sum(value) OVER (ORDER BY taken_at ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS sum_row_frame,
-- first_value 会看帧:默认帧帧头固定,ROWS 帧头是上一行
first_value(value) OVER (ORDER BY taken_at) AS fv_default,
first_value(value) OVER (ORDER BY taken_at ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS fv_row_frame
FROM readings
ORDER BY taken_at;Same frame clause, two different contracts
Every OVER in this query computes over rows ordered by taken_at, and half of them carry an extra ROWS BETWEEN 1 PRECEDING AND CURRENT ROW. The ranking functions do not care: rank() numbers rows 1–4 in both variants because ranking is defined over the partition’s peer set, never the frame. The aggregates do care: sum(value) over the default frame is the running total, while the ROWS-frame sum adds only the previous row and the current one. first_value(value) also honors the frame — with the default frame the head is fixed at the partition’s first row, with the ROWS frame it is the preceding row.
The full result, four columns at a time
taken_at | value | rank_default | rank_row_frame | sum_default | sum_row_frame | fv_default | fv_row_frame
---------+-------+--------------+----------------+-------------+---------------+------------+--------------
09:00 | 10 | 1 | 1 | 10 | 10 | 10 | 10
09:05 | 20 | 2 | 2 | 30 | 30 | 10 | 20
09:10 | 30 | 3 | 3 | 60 | 50 | 10 | 30
09:15 | 40 | 4 | 4 | 100 | 70 | 10 | 40
Read the rank_* pair as identical and the sum_*/fv_* pairs as diverging — that asymmetry is the lesson: a frame clause changes aggregate and first_value results while leaving rank, row_number, lag, and ntile untouched.
The line that differs only by its frame
sum(value) OVER (ORDER BY taken_at ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS sum_row_frame,
At 09:10 this yields 50 (30 + 20) where the default-frame column yields 60 (the running total) — one clause, different denominators.
Interactive Tools for This Topic
FAQ
- Which tables does this file reference?
- `readings` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.