Function Reference

LEAD

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

MySQL 8.1
LEAD(column[, offset[, default]])
  • [ ]optional part
column
Column or expression whose value is taken from the next row
offset
How many rows ahead 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 last row of a partition

Examples

Shift one and two rows forward

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

Free days before the next reservation

MySQL 8.1
SELECT room_id,
	start_date,
	end_date,
	DATEDIFF(
		LEAD(start_date) OVER (
			PARTITION BY room_id
			ORDER BY start_date
		),
		end_date
	) AS free_days_after
FROM Reservations;
room_idstart_dateend_datefree_days_after
12018-10-09 12:00:002018-10-12 12:00:0032
12018-11-13 12:00:002018-11-15 12:00:0044
12018-12-29 12:00:002019-01-07 12:00:0025
12019-02-01 12:00:002019-02-02 12:00:000
12019-02-02 12:00:002019-02-04 12:00:00<NULL>
22020-03-21 09:00:002020-03-23 09:00:00<NULL>
52020-03-26 10:00:002020-03-27 10:00:0048
52020-05-14 10:00:002020-05-15 10:00:00<NULL>
72019-09-13 10:00:002019-09-17 10:00:00<NULL>
82020-01-19 12:00:002020-01-21 12:00:00<NULL>

Details

LEAD is handy for calculating the gap before the next event: for example, how many days a room stays free until the next reservation. 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