Lecture

LEAD and LAG

LEAD() and LAG() are window functions that allow you to look at other rows relative to the current row's position, without needing joins.

  • LEAD() looks forward to the next row.
  • LAG() looks backward to the previous row.

These are useful for comparisons across rows, such as tracking changes in user progress or viewing 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 (...)

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 see the progress of each user over time, and compare it to the previous and next day's progress.

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

You can use LEAD() and LAG() to compare the progress of each user over time.

Quiz
0 / 1

What is the primary purpose of the PARTITION BY clause in SQL window functions?

To collapse rows into a single summary row like GROUP BY.

To filter out rows that do not meet certain criteria.

To divide rows into groups for independent processing.

To join multiple tables together based on common columns.

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Tables

Execution Result