r/SQL • • 17m ago

Discussion LAST_VALUE kept giving me the current row instead of the last one. the default window frame was the reason

wanted the latest order amount next to every order for each customer, so i wrote this:

SELECT customer_id, order_date, amount,
LAST_VALUE(amount) OVER (
PARTITION BY customer_id ORDER BY order_date
) AS last_amt
FROM orders;

and got this:

customer_id | order_date | amount | last_amt
1 | 2025-01-05 | 40 | 40
1 | 2025-02-11 | 25 | 25
1 | 2025-03-02 | 60 | 60
2 | 2025-01-20 | 90 | 90
2 | 2025-02-28 | 15 | 15

last_amt is just amount again. FIRST_VALUE on the same window worked fine, which made it more confusing

the reason: once you put ORDER BY inside OVER, the default frame is `RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`. so the "last" row of the frame is always the current row (or its last tie). FIRST_VALUE doesnt care because the start of the frame is still the first row

fix is to spell out the frame:

LAST_VALUE(amount) OVER (
PARTITION BY customer_id ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_amt

now customer 1 gets 60 on every row and customer 2 gets 15

or skip LAST_VALUE and flip the sort: `FIRST_VALUE(amount) OVER (PARTITION BY customer_id ORDER BY order_date DESC)` gives the same result

same default frame in postgres, sql server, mysql 8 and sqlite (tested on sqlite). also the reason a running SUM can act weird when two rows have the same date, since RANGE treats ties as one group

anyone actually use LAST_VALUE with the full frame or do you all just do the FIRST_VALUE DESC trick?

1 Upvotes

1 comment sorted by

1

u/Eleventhousand 14m ago

I probably use last_value with unbounded following.