Function Reference

LAG

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

MySQL 8.4
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, a non-negative integer, 1 by default
INTOptional
default
Value 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

MySQL 8.4
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

Days since the previous payment of each family member

MySQL 8.4
SELECT family_member,
	date,
	DATEDIFF(
		date,
		LAG(date) OVER (
			PARTITION BY family_member
			ORDER BY date
		)
	) AS days_since_previous
FROM Payments;
family_memberdatedays_since_previous
12005-02-03<NULL>
12005-02-129
12005-03-1127
12005-04-2040
12005-05-1323
12005-06-0523
12006-01-15224
12006-03-1256
22005-03-18<NULL>
22005-03-235

Details

A typical task is to compare a row with the previous one: the difference x - LAG(x) OVER (...) or DATEDIFF(date, LAG(date) OVER (...)) shows the change since the previous row. default is used only when there is no row at that offset; if the row exists but holds NULL, the result is NULL.

See also

Where to learn