LAST_VALUE() in SQL
Returns the last value in an ordered partition of a result set.
Syntax
Return type
LAST_VALUE() Function Example
What is LAST_VALUE() in SQL?
The LAST_VALUE()
function in SQL returns the last value within an ordered partition of a result set. It is commonly used for retrieving the most recent record, identifying the latest transaction, and comparing current values to the last value in a dataset.
This function is supported in SQL Server, PostgreSQL, MySQL 8.0+, and Oracle as part of window functions.
This function is widely used in trend analysis, financial reporting, and tracking the most recent data points.
Parameters:
expression: Column or expression to retrieve
frame_clause (recommended): Defines window frame boundaries
Example Use Cases:
-- Compare to worst performing product
-- Track closing price
-- Final score in competition
Notes:
Behavior: Returns NULL if partition is empty
Performance Considerations: Window frame specification important for correct results
Version Info: Core window function available in most modern DBMS
Deprecated/Recommended Alternatives: None, standard functionality
Error Handling:
Error: May give unexpected results without proper frame clause
Recommendation: Always specify frame clause ROWS/RANGE BETWEEN
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
LAST_VALUE()
LAST_VALUE(col) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
Returns NULL
PostgreSQL
LAST_VALUE()
LAST_VALUE(col) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
Returns NULL
SQL Server
LAST_VALUE()
LAST_VALUE(col) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
Returns NULL
SQLite
LAST_VALUE()
LAST_VALUE(col) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
Returns NULL
BigQuery
LAST_VALUE()
LAST_VALUE(col) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
Returns NULL
Snowflake
LAST_VALUE()
LAST_VALUE(col) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
Returns NULL
Athena
LAST_VALUE()
LAST_VALUE(col) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
Returns NULL
Related Functions:
FIRST_VALUE()
Returns the first value in an ordered partition of a result set.
LEAD()
Accesses data from a subsequent row in the result set within a specified window partition.
LAG()
Accesses data from a previous row in the result set within a specified window partition.
ROW_NUMBER()
Assigns a unique sequential integer to rows within a result set partition.