Window
LAST_VALUE()
Overview
The LAST_VALUE()
is a window function that retrieves the last value in an ordered set of values within a specified partition.
Syntax
The syntax for this function is as follows:
Parameters
expression
: input’s column or expression values that returns a single value. It represents the value you want to retrieve from the first row of the sorted partitionPARTITION BY
: optional clause, which divides the result set into partitions to which theLAST_VALUE()
function is applied (if omitted, the entire result set is treated as a single partition)ORDER BY
: order of rows in each partition to which the function is appliedRANGE BETWEEN
: range-based window frame relative to the current row
Example
For the needs of this section, we will use a simplified version of the film
table from the Pagila database, containing only the title
, length
and rating
columns. The complete schema for the film
table can be found on the
Pagila website.
The query below uses the LAST_VALUE()
function to retrieve the title of the film with the longest duration, partitioning results by rating and ordering by length.
By running the code above, we will get the following output: