LAG / LEAD
Window Functions
Master row-by-row comparisons in SQL by reaching backward with LAG and forward with LEAD across ordered result sets.
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.
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.
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.
The Syntax
1NULLPARTITION BY Explained
PARTITION BY divides rows into independent groups. LAG/LEAD only look within the same partition: they never cross the boundary.
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
COALESCE.Example 1: Basic LAG
Calculate the month-over-month change in revenue:
Example 2: Basic LEAD
Preview the next day's temperature alongside today's:
Example 3: Offset Greater Than 1
Compare this quarter's sales to the same quarter last year (4 quarters back):
Example 4: PARTITION BY + LAG
Track each student's grade change across assignments, independently per student:
Handling NULL Defaults
The third argument of LAG/LEAD specifies what to return when there is no row at the requested offset:
Common Mistakes
ORDER BY inside OVER(), the row order is undefined. LAG/LEAD return unpredictable results.PARTITION BY when groups exist means LAG compares across different groups (e.g., different customers blended together).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?
LEAD(salary) gives you the next colleague's salary. LAG would give the previous colleague's salary.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?