LAST_VALUE Default Frame Pitfall

Show why LAST_VALUE returns the current row under the default frame and how ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING restores the real tail.

SqlData Integrity

Code

snippet
WITH readings(sensor_id, taken_at, celsius) AS (
    VALUES
        (1, '09:00'::time, 21.0),
        (1, '09:10'::time, 22.5),
        (1, '09:20'::time, 24.0),
        (2, '09:00'::time, 18.0),
        (2, '09:10'::time, 17.0)
)
SELECT
    sensor_id,
    taken_at,
    celsius,
    -- 默认帧是 RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW:
    -- LAST_VALUE 停在当前行,看起来像“没生效”
    LAST_VALUE(celsius) OVER w AS last_default_frame,
    -- 帧显式延伸到分区末尾,才是分区里真正的最后一个值
    LAST_VALUE(celsius) OVER (
        PARTITION BY sensor_id
        ORDER BY taken_at
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    ) AS last_full_frame
FROM readings
WINDOW w AS (PARTITION BY sensor_id ORDER BY taken_at)
ORDER BY sensor_id, taken_at;

How the snippet works

At its core this is a single SELECT statement against readings.

What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

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.

Using it

Run the statement against the readings table.

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`readings`.