Categories:

Window Functions (Rank-related, Window Frame)

# LAST_VALUE¶

Returns the last value within an ordered group of values.

## Syntax¶

LAST_VALUE( <expr> ) [ { IGNORE | RESPECT } NULLS ]
OVER ( [ PARTITION BY <expr1> ] ORDER BY <expr2> [ { ASC | DESC } ] [ <window_frame> ] )


For details about window_frame syntax, see Window Frame Syntax and Usage.

## Usage Notes¶

• For compatibility with implementations of this function in other systems, { IGNORE | RESPECT } NULLS can also be specified in the arguments for the function:

LAST_VALUE( <expr> [ { IGNORE | RESPECT } NULLS ] ) OVER ...

• If { IGNORE | RESPECT } NULLS is not specified, the default is RESPECT NULLS, i.e. a NULL value is returned if the expression contains a NULL value and it is the last value in the expression.

• LAST_VALUE is a rank-related function so it requires a window to be specified, consisting of the following elements:

• PARTITION BY <expr1> subclause (optional).

• ORDER BY <expr2> subclause (required) with an optional window_frame. For more details about additional supported ordering options (sort order, ordering of NULL values, etc.), see the ORDER BY query construct.

• The optional window_frame (cumulative or sliding) specifies the subset of rows within the window for which the function is calculated.

• For window frames, this function supports only ROWS-based window frames, not RANGE-based window frames.

Supported

ROWS BETWEEN ... AND ...

Not supported

RANGE BETWEEN ... AND ...

• If no window_frame is specified, the default is the entire window:

ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING

This differs from the ANSI standard, which specifies the following default for window frames:

RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW

For more details about window frames, including syntax and examples, see Window Frame Syntax and Usage.

## Examples¶

SELECT
column1,
column2,
LAST_VALUE(column2) OVER (PARTITION BY column1 ORDER BY column2) AS column2_last
FROM VALUES
(1, 10), (1, 11), (1, 12),
(2, 20), (2, 21), (2, 22);

+---------+---------+--------------+
| COLUMN1 | COLUMN2 | COLUMN2_LAST |
|---------+---------+--------------|
|       1 |      10 |           12 |
|       1 |      11 |           12 |
|       1 |      12 |           12 |
|       2 |      20 |           22 |
|       2 |      21 |           22 |
|       2 |      22 |           22 |
+---------+---------+--------------+