// window reference

SQL LAST_VALUE function

Returns an expression from the last row of the window frame. The famous trap: the default frame ends at the current row, so naive LAST_VALUE returns the row you are on.

Category
Window
Returns
type of the expression
In this category
8 of 79

Syntax

LAST_VALUE(expression) OVER (ORDER BY x ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)

Engine support

EngineSupportNotes
SQL Server Yes Supported under this name.
PostgreSQL Yes Supported under this name.
MySQL Yes MySQL 8.0+
SQLite Yes SQLite 3.25+
Oracle Yes Supported under this name.

Examples

Any engine

-- returns the day's own price without the frame fix!
SELECT day, price,
       LAST_VALUE(price) OVER (ORDER BY day) AS wrong
FROM prices;

Any engine

-- the correct form
SELECT day, price,
       LAST_VALUE(price) OVER (
         ORDER BY day
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS close_price
FROM prices;

Good to know

  • The default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so LAST_VALUE(price) OVER (ORDER BY day) returns the current row's price. The fix is an explicit frame: ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
  • FIRST_VALUE does not hit this, because the default frame always starts at the partition's first row. It only reaches the partition's last row on that last row.
  • With RANGE (the default) and ties in the ORDER BY, LAST_VALUE returns the last of the current row's peers, not the current row, which makes the wrong result harder to spot.

Questions about LAST_VALUE

Why does LAST_VALUE return the current row?

The default window frame stops at the current row, so the last row of the frame is the row you are on. Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to stretch the frame over the whole partition.

Is there an easier way to get the last row's value?

Yes: FIRST_VALUE with the order reversed. FIRST_VALUE(price) OVER (ORDER BY day DESC) returns the last day's price with the default frame, no frame clause needed.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.