01 / 20
LAG LEAD

LAG / LEAD
Window Functions

Master row-by-row comparisons in SQL by reaching backward with LAG and forward with LEAD across ordered result sets.

Computer Science SQL Window Functions

What Are Window Functions?

Regular aggregate functions like SUM or AVG collapse many rows into one. A window function performs a calculation across a set of rows that are related to the current row: without collapsing them.

OVER()
Defines which rows the function can see: the "window"
ORDER BY
Sorts the rows inside the window so "previous" and "next" have meaning

Meet LAG and LEAD

LAG reaches backward to a previous row. LEAD reaches forward to a following row. Both return the value of a column from that offset row.

Row \( n-1 \)
Current Row \( n \)
Row \( n+1 \)
LAG LEAD Direction of Lookup LAG: look at a previous row LEAD: look at a following row

Why Use LAG / LEAD?

Before window functions, comparing a row to its neighbor required messy self-joins or correlated subqueries. LAG and LEAD let you do it in one clean pass.

Month-over-Month
Compare this month's revenue to last month's
Running Deltas
Calculate day-over-day temperature change
Gap Detection
Find missing sequence numbers or time gaps

The Syntax

LAG(column, offset, default) OVER ( PARTITION BY group_col ORDER BY sort_col ) LEAD(column, offset, default) OVER ( PARTITION BY group_col ORDER BY sort_col )
1
column: the value you want to retrieve from the offset row
2
offset: how many rows back (LAG) or forward (LEAD): defaults to 1
3
default: value returned when there is no row at that offset (e.g., the first row has no previous row): defaults to NULL

PARTITION BY Explained

PARTITION BY divides rows into independent groups. LAG/LEAD only look within the same partition: they never cross the boundary.

Partition: East Jan: $10k Feb: $12k Mar: $15k LAG Partition: West Jan: $8k Feb: $9k Mar: $11k LAG No cross-partition access

LAG vs LEAD: Key Distinction

LAG LEAD
Direction Backward (previous rows) Forward (following rows)
Default offset 1 (one row back) 1 (one row ahead)
NULL on First row(s) in partition Last row(s) in partition
Common Use "What was last month?" "What is next month?"
Equivalent LAG(x, 1) LEAD(x, 1)

How to Apply LAG / LEAD

1
Identify the comparison: Do you need a previous value (LAG) or a future value (LEAD)?
2
Choose the column: Which column's value do you want from the offset row?
3
Set ORDER BY: Define the row sequence (e.g., by date, by id). Without this, "previous" has no meaning.
4
Add PARTITION BY (optional): If comparisons should restart per group (e.g., per customer, per region).
5
Handle NULLs: Provide a default value as the third argument, or use COALESCE.

Example 1: Basic LAG

Calculate the month-over-month change in revenue:

SELECT month, revenue, LAG(revenue, 1, 0) OVER (ORDER BY month) AS prev_rev, revenue - LAG(revenue, 1, 0) OVER (ORDER BY month) AS change FROM monthly_sales;
month revenue prev_rev change Jan 100 0 100 Feb 150 100 50 Mar 130 150 -20 Apr 200 130 70

Example 2: Basic LEAD

Preview the next day's temperature alongside today's:

SELECT day, temp, LEAD(temp) OVER (ORDER BY day) AS next_temp FROM weather;
day temp next_temp Mon 72 68 Tue 68 75 Wed 75 80 Thu 80 NULL

Example 3: Offset Greater Than 1

Compare this quarter's sales to the same quarter last year (4 quarters back):

SELECT quarter, sales, LAG(sales, 4) OVER (ORDER BY quarter) AS same_q_last_yr, sales - LAG(sales, 4) OVER (ORDER BY quarter) AS yoy_change FROM quarterly_report;

Example 4: PARTITION BY + LAG

Track each student's grade change across assignments, independently per student:

SELECT student, assignment, grade, grade - LAG(grade) OVER ( PARTITION BY student ORDER BY assignment ) AS improvement FROM grades;

Handling NULL Defaults

The third argument of LAG/LEAD specifies what to return when there is no row at the requested offset:

-- Returns 0 instead of NULL for the first row LAG(revenue, 1, 0) OVER (ORDER BY month) -- Alternative: wrap in COALESCE COALESCE( LAG(revenue) OVER (ORDER BY month), 0 )
Third Argument
Cleaner syntax, but only accepts a literal or expression: cannot reference other columns
COALESCE
More flexible: can substitute with another column, a subquery result, or complex logic

Common Mistakes

✕ Missing ORDER BY
Without ORDER BY inside OVER(), the row order is undefined. LAG/LEAD return unpredictable results.
✕ Forgetting PARTITION BY
Omitting PARTITION BY when groups exist means LAG compares across different groups (e.g., different customers blended together).
✕ Ignoring NULLs
The first row for LAG (or last for LEAD) is NULL by default. Arithmetic on NULL produces NULL, silently breaking calculations.

Quick Reference Table

Feature LAG LEAD
Looks at Previous row(s) Following row(s)
Default offset 1 1
NULL position First row(s) Last row(s)
Requires OVER (ORDER BY ...)
Optional PARTITION BY, default value
Use case Prior period compare Future period preview

Question 1 of 5

What does LAG(price, 1) return for the first row in a partition (assuming no default is specified)?

Question 2 of 5

Which clause is required inside OVER() for LAG and LEAD to produce meaningful results?

Question 3 of 5

You want to compare each employee's salary to their next colleague's salary (ordered by hire date). Which function do you use?

Question 4 of 5

Given LAG(score, 2, -1) OVER (ORDER BY game_date), what does the -1 represent?

Question 5 of 5

What happens if you omit PARTITION BY from a LAG/LEAD window function?