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.
Code
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-levelWHEREwill not work — use an outer query or a CTE.
Using it
Run the statement against the readings table.
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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- `readings`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.