LEAD Function in SQL

Level 5202 keystrokes

LEAD accesses data from a following row in the result set.

SQL code

-- Return each event with the date of the next event
1SELECT
2 event_date,
3 event_name,
-- LEAD(event_date, 1) reads event_date from 1 row ahead, in date order
4 LEAD(event_date, 1) OVER (
5 ORDER BY event_date
-- The last event has no next row, so it gets NULL
6 ) AS next_event_date,
-- DATEDIFF(later, earlier) gives the number of days between two dates
7 DATEDIFF(
-- The window function is repeated here because the alias cannot be reused in SELECT
8 LEAD(event_date, 1) OVER (ORDER BY event_date),
9 event_date
-- For the last event the difference is NULL too
10 ) AS days_until_next
-- No ORDER BY at the end, so the display order is not guaranteed
11FROM
12 events;

Output

+------------+------------+-----------------+-----------------+
| event_date | event_name | next_event_date | days_until_next |
+------------+------------+-----------------+-----------------+
| 2024-01-15 | Launch     | 2024-01-22      |               7 |
| 2024-01-22 | Update     | 2024-02-01      |              10 |
| 2024-02-01 | Release    | NULL            |            NULL |
+------------+------------+-----------------+-----------------+
3 rows in set
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this SQL code and how often they appear.

  • _× 11
  • ,× 6
  • (× 5
  • )× 5
  • ;× 1

More SQL examples at level 5

← SQL typing practice