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
Syntax
last_value(value) OVER (... ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
Parameters
| Parameter | Description |
|---|---|
value |
The expression to read. |
Return value
The value.
Examples
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.
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
| Version | Change |
|---|---|
| PostgreSQL 8.4 | Added |
In other languages
LAST_VALUE()· SQLite
Related
FIRST_VALUE()· Return a value from the first row of the window frame, such as each department's highest salary.NTH_VALUE()· Return a value from the nth row of the window frame, or NULL if the frame has fewer rows.- SQL Window Functions · tutorial