WindowSQL standard

FIRST_VALUE

Takes the value from the first row of the window.

Syntax

FIRST_VALUE(<expression>) OVER (ORDER BY <sort key>)
FIRST_VALUE(<expression>) OVER (PARTITION BY <group> ORDER BY <sort key>)

Adds to every row the value from the first row of its window: the highest salary in the company, the name of the department's leader. The number of rows stays the same, so it's easy to compare side by side: how far each person is from the first. Its mirror function is LAST_VALUE, but that one needs its window frame set up.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

The highest salary next to each one
SELECT name, salary,
FIRST_VALUE(salary) OVER (ORDER BY salary DESC) AS top_salary
FROM employees;
namesalarytop_salary
Olivia13501350
Emma12001350
Sophia12001350
Liam10001350
Noah9501350
The leader of each department
SELECT name, department, salary,
FIRST_VALUE(name) OVER (PARTITION BY department ORDER BY salary DESC) AS leader
FROM employees;
namedepartmentsalaryleader
Emmabackend1200Emma
Liambackend1000Emma
Sophiadesign1200Sophia
Oliviafrontend1350Olivia
Noahfrontend950Olivia
How far each salary is from the highest
SELECT name, salary,
FIRST_VALUE(salary) OVER (ORDER BY salary DESC) - salary AS gap_to_top
FROM employees;
namesalarygap_to_top
Olivia13500
Emma1200150
Sophia1200150
Liam1000350
Noah950400

Watch out

With equal values, any of the tied rows can become “first”. For a stable result, add a unique field to ORDER BY.

Unlike with LAST_VALUE, the window frame doesn't get in the way here: the window always starts at the first row. So the “last” value is easier to get as FIRST_VALUE with the order reversed.

You can't use the result in the WHERE of the same query — calculate it in a subquery first and filter outside it.

Related functions

Learn more in the course