Function Reference

LEAD

Returns the value from the row that is offset rows after the current one in the window partition.

PostgreSQL 17.5
LEAD(column[, offset[, default]]) OVER ([PARTITION BY ...] [ORDER BY ...])

Parameters

column
Column or expression whose value is taken from the next row
offsetintegeroptional
How many rows ahead to look, 1 by default; a negative value looks back, like LAG
defaultoptional
Value of the same type as column used if there is no row at that offset, NULL by default
PARTITION BYoptional
Columns that split rows into partitions, the offset does not cross partition bounds
ORDER BYoptional
Order of rows that defines which row is the next one

Return value

A value of the same type as column; default or NULL if there is no row at that offset, for example for the last row of a partition

Examples

Shift one and two rows forward

PostgreSQL 17.5
SELECT member_name,
	birthday,
	LEAD(member_name) OVER (
		ORDER BY birthday
	) AS next_member,
	LEAD(member_name, 2, 'none') OVER (
		ORDER BY birthday
	) AS two_rows_ahead
FROM FamilyMembers;
member_namebirthdaynext_membertwo_rows_ahead
Headley Quincey1960-05-13Ernest ForrestFlavia Quincey
Ernest Forrest1961-09-11Flavia QuinceyConstance Forrest
Flavia Quincey1963-02-16Constance ForrestAndie Quincey
Constance Forrest1968-09-06Andie QuinceyLela Quincey
Andie Quincey1983-06-05Lela QuinceyAnnie Quincey
Lela Quincey1985-06-07Annie QuinceyWednesday Addams
Annie Quincey1988-04-10Wednesday Addamsnone
Wednesday Addams2005-01-13<NULL>none

Time until the next purchase

PostgreSQL 17.5
SELECT family_member,
	date,
	LEAD(date) OVER (
		PARTITION BY family_member
		ORDER BY date
	) AS next_date,
	LEAD(date) OVER (
		PARTITION BY family_member
		ORDER BY date
	) - date AS until_next
FROM Payments
ORDER BY family_member,
	date;
family_memberdatenext_dateuntil_next
12005-02-032005-02-129 days
12005-02-122005-03-1127 days
12005-03-112005-04-2040 days
12005-04-202005-05-1323 days
12005-05-132005-06-0523 days
12005-06-052006-01-15224 days
12006-01-152006-03-1256 days
12006-03-12<NULL><NULL>
22005-03-182005-03-235 days
22005-03-232005-06-1180 days

Details

The difference from the next row is LEAD(column) OVER (...) - column: for the last row of a partition it is NULL. default must be of the same type as column.

See also

Where to learn