PostgreSQL 18 reference · Window Functions

PostgreSQL LAST_VALUE() Function

Return a value from the last row of the window frame. Widen the frame or it returns the current row.

PostgreSQL 18 Since 8.4

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

last_value(value) OVER (... ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)

Parameters

ParameterDescription
value The expression to read.

Return value

The value.

Examples

Why the frame matters
SELECT name, salary,
       last_value(name) OVER (ORDER BY salary) AS default_frame,
       last_value(name) OVER (ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS whole
FROM employees
WHERE department = 'Sales';

Output

     name      | salary | default_frame |     whole
---------------+--------+---------------+---------------
 Emma Novak    |  88000 | Emma Novak    | Hannah Okafor
 Diego Silva   |  90000 | Diego Silva   | Hannah Okafor
 Hannah Okafor | 150000 | Hannah Okafor | Hannah Okafor
(3 rows)

Run this on your computer — see “Get Started” for setup.

Latest hire per department
SELECT DISTINCT department,
       last_value(hire_date) OVER (PARTITION BY department ORDER BY hire_date
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS latest_hire
FROM employees
ORDER BY department;

Output

 department  | latest_hire
-------------+-------------
 Engineering | 2023-08-28
 Management  | 2018-03-01
 Sales       | 2024-01-08
 Support     | 2024-10-01
(4 rows)

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
PostgreSQL 8.4Added

In other languages

Was this page helpful?