Lecture

LEAD and LAG

LEAD() and LAG() are window functions that let you access values from rows before or after the current one, without using joins.

  • LEAD() returns values from following rows.
  • LAG() returns values from preceding rows.

These functions are useful for row-to-row comparisons, such as tracking changes in progress or examining adjacent data points.

Syntax

The basic syntax for LEAD() and LAG() is as follows:

LEAD and LAG syntax
SELECT column, LAG(column) OVER (ORDER BY ...) AS previous_value, LEAD(column) OVER (ORDER BY ...) AS next_value FROM table;

You can also provide default values and custom offsets:

LAG syntax with default values and custom offsets
LAG(column, offset, default_value) OVER (...)

By default, offset = 1 and default_value = NULL.


Example: CodeFriends Progress

Assume we have the following table:

Table: course_progress

user_idlog_datecourse_nameprogress_percent
12024-06-01SQL Basics40
12024-06-02SQL Basics60
12024-06-03SQL Basics80
12024-06-04SQL Basics100

We want to compare each day’s progress to the previous and next day for every user.

LEAD and LAG example
SELECT user_id, log_date, course_name, progress_percent, LAG(progress_percent) OVER (PARTITION BY user_id ORDER BY log_date) AS previous_progress, LEAD(progress_percent) OVER (PARTITION BY user_id ORDER BY log_date) AS next_progress FROM course_progress;

The query returns the following:

Result:

user_idlog_datecourse_nameprogress_percentprevious_progressnext_progress
12024-06-01SQL Basics40NULL60
12024-06-02SQL Basics604080
12024-06-03SQL Basics8060100
12024-06-04SQL Basics10080NULL

When are LEAD and LAG useful?

  • Use LAG() to compare a row with earlier values (e.g., progress since the previous day).
  • Use LEAD() to compare a row with upcoming values (e.g., forecast next step or change).

In practice, they’re often used for time-series analysis, trend tracking, and change detection.

Quiz
0 / 1

What is the main purpose of the LAG() function in SQL?

To access a value from the previous row without using a join.

To return values from the next row in the result set.

To divide rows into equal-sized groups based on ordering.

To generate a unique sequential number for each row.

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Tables

Execution Result