PostgreSQL 18 reference · Window Functions

PostgreSQL FIRST_VALUE() Function

Return a value from the first row of the window frame, such as each department's highest salary.

PostgreSQL 18 Since 8.4

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

Syntax

first_value(value) OVER (PARTITION BY ... ORDER BY ...)

Parameters

ParameterDescription
value The expression to read.

Return value

The value.

Examples

The top of each partition
SELECT department, name, first_value(name) OVER (PARTITION BY department ORDER BY salary DESC) AS top_earner
FROM employees
WHERE department IN ('Sales', 'Support');

Output

 department |     name      |  top_earner
------------+---------------+---------------
 Sales      | Hannah Okafor | Hannah Okafor
 Sales      | Diego Silva   | Hannah Okafor
 Sales      | Emma Novak    | Hannah Okafor
 Support    | Ravi Kumar    | Ravi Kumar
(4 rows)

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

Compare with the first row
SELECT name, salary, salary - first_value(salary) OVER (ORDER BY salary) AS above_lowest
FROM employees
ORDER BY salary
LIMIT 3;

Output

    name     | salary | above_lowest
-------------+--------+--------------
 Ravi Kumar  |  65000 |            0
 Emma Novak  |  88000 |        23000
 Diego Silva |  90000 |        25000
(3 rows)

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

Version history

VersionChange
PostgreSQL 8.4Added

In other languages

Was this page helpful?