Skip to content

LAST_VALUE

LAST_VALUE(expression) OVER ( [PARTITION BY partition_expression, … ] ORDER BY sort_expression [ASC | DESC], … [frame_specification])

Section titled “LAST_VALUE(expression) OVER ( [PARTITION BY partition_expression, … ] ORDER BY sort_expression [ASC | DESC], … [frame_specification])”
  • expression: This is the value to be returned as the last value in the ordered partition. It is a column or a formula within the function LAST_VALUE().
  • partition by partition_expression: It is used to divide the result set into partitions where function is applied separately for each. It is optional.
  • order by sort_expression [asc | desc]: This parameter is used to order the rows within each partition. It can be ascending (ASC) or descending (DESC).
  • frame_specification: Specifies the range of rows within a partition to be used for the calculation, such as “ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING”. It is optional in some databases but required in others.
CREATE TABLE example (
id INT,
some_value INT
);
INSERT INTO example (id, some_value)
VALUES
(1, 10),
(2, 20),
(3, 30);
SELECT
id,
LAST_VALUE(some_value) OVER (ORDER BY id) AS LastValue
FROM
example
idLastValue
110
220
330

In the SQL script provided, a table example with two columns id and some_value is created. Three records are inserted into this table. The LAST_VALUE function retrieves the last value in the ordered (by id) partition of some_value for each row in example. From the output, it’s clear the LastValue column shows the current maximum some_value encountered in the ordered set up to the current row.