PostgreSQL 18 reference · Window Functions

PostgreSQL NTH_VALUE() Function

Return a value from the nth row of the window frame, or NULL if the frame has fewer rows.

PostgreSQL 18 Since 8.4

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

Syntax

nth_value(value, n) OVER (PARTITION BY ... ORDER BY ...)

Parameters

ParameterDescription
value The expression to read.
n The row within the frame, from 1.

Return value

The value, or NULL.

Examples

Second-highest salary
SELECT DISTINCT nth_value(name, 2) OVER (ORDER BY salary DESC
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second_highest_paid
FROM employees;

Output

 second_highest_paid
---------------------
 Omar Haddad
(1 row)

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

NULL until the frame reaches row 3
SELECT name, nth_value(name, 3) OVER (ORDER BY hire_date) AS third_hire
FROM employees
LIMIT 4;

Output

     name      |  third_hire
---------------+---------------
 Sofia Reyes   | NULL
 Omar Haddad   | NULL
 Hannah Okafor | Hannah Okafor
 Mei Chen      | Hannah Okafor
(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?