last_value
Returns the last value in the current ordered window frame. The function selects a row position; it retains a NULL at that position.
The default ordered frame ends at the current peer group. Use ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to read the last value of the whole partition.
Syntax
text
last_value(value) OVER (
[PARTITION BY expression, ...]
ORDER BY expression, ...
[ROWS | RANGE | GROUPS frame_bounds]
)Arguments
value— The expression evaluated at the selected row.
Returned value
The selected input value, preserving its native type. An empty frame returns NULL. Frame exclusions apply before selecting the position.
Examples Reading from a growing frame
The frame starts at the first sale and ends at the current row:
sql
CREATE TABLE sales (day INTEGER, amount INTEGER);
INSERT INTO sales VALUES (1, 120), (2, 150), (3, 90);sql
SELECT day, amount,
last_value(amount) OVER (
ORDER BY day
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS selected_amount
FROM sales
ORDER BY day
FORMAT csv;text
1,120,120
2,150,150
3,90,90Reading the last value of the whole partition
sql
SELECT day,
last_value(amount) OVER (
ORDER BY day
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS final_amount
FROM sales
ORDER BY day
FORMAT csv;text
1,90
2,90
3,90See window functions for supported frame units and exclusions.