Function Reference

LAG

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

PostgreSQL 17.9
LAG(column[, offset[, default]])
  • [ ]optional part
column
Column or expression whose value is taken from the previous row
offset
How many rows back to look, 1 by default; a negative value looks ahead, like LEAD
integerOptional
default
Value of the same type as column used if there is no row at that offset, NULL by default
Optional

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 first row of a partition

Examples

Shift one and two rows back

PostgreSQL 17.9
SELECT member_name,
	birthday,
	LAG(member_name) OVER (
		ORDER BY birthday
	) AS previous_member,
	LAG(member_name, 2, 'none') OVER (
		ORDER BY birthday
	) AS two_rows_back
FROM FamilyMembers;
member_namebirthdayprevious_membertwo_rows_back
Headley Quincey1960-05-13<NULL>none
Ernest Forrest1961-09-11Headley Quinceynone
Flavia Quincey1963-02-16Ernest ForrestHeadley Quincey
Constance Forrest1968-09-06Flavia QuinceyErnest Forrest
Andie Quincey1983-06-05Constance ForrestFlavia Quincey
Lela Quincey1985-06-07Andie QuinceyConstance Forrest
Annie Quincey1988-04-10Lela QuinceyAndie Quincey
Wednesday Addams2005-01-13Annie QuinceyLela Quincey

Time since the previous purchase

PostgreSQL 17.9
SELECT family_member,
	date,
	LAG(date) OVER (
		PARTITION BY family_member
		ORDER BY date
	) AS previous_date,
	date - LAG(date) OVER (
		PARTITION BY family_member
		ORDER BY date
	) AS since_previous
FROM Payments
ORDER BY family_member,
	date;
family_memberdateprevious_datesince_previous
12005-02-03<NULL><NULL>
12005-02-122005-02-039 days
12005-03-112005-02-1227 days
12005-04-202005-03-1140 days
12005-05-132005-04-2023 days
12005-06-052005-05-1323 days
12006-01-152005-06-05224 days
12006-03-122006-01-1556 days
22005-03-18<NULL><NULL>
22005-03-232005-03-185 days

Details

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

See also

Where to learn