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.
- カテゴリ
- ウィンドウ
- Returns
type of the expression- In this category
- 8 of 79
構文
LAST_VALUE(expression) OVER (ORDER BY x ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | はい | Supported under this name. |
| PostgreSQL | はい | Supported under this name. |
| MySQL | はい | MySQL 8.0+ |
| SQLite | はい | SQLite 3.25+ |
| Oracle | はい | Supported under this name. |
例
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;
知っておくと便利なこと
- 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.
Related on SQLly
- First and last value in a partition Snippet
- SQL window function interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.