SQL LAG and LEAD
LAG reads a value from an earlier row and LEAD from a later one, in the order you choose. They’re how you calculate change over time without a self-join.
Updated December 1, 2026
Syntax
LAG(column, offset, default) OVER (ORDER BY sort_column)
LEAD(column, offset, default) OVER (ORDER BY sort_column)
Change from the previous day
Drinks sold each day, the day before, and the difference. The first day has no previous row, so LAG returns NULL.
SELECT ordered_on, SUM(quantity) AS sold,
LAG(SUM(quantity)) OVER (ORDER BY ordered_on) AS prev_day,
SUM(quantity) - LAG(SUM(quantity)) OVER (ORDER BY ordered_on) AS change
FROM orders
GROUP BY ordered_on;
| ordered_on | sold | prev_day | change |
|---|---|---|---|
| 2024-07-01 | 3 | NULL | NULL |
| 2024-07-02 | 2 | 3 | -1 |
| 2024-07-03 | 4 | 2 | 2 |
| 2024-07-04 | 2 | 4 | -2 |
| 2024-07-05 | 3 | 2 | 1 |
| 2024-07-06 | 1 | 3 | -2 |
Time until the next event
LEAD looks ahead: days between each signup and the next one with the same email.
SELECT email, signed_up,
LEAD(signed_up) OVER (PARTITION BY email ORDER BY signed_up) AS next_signup,
julianday(LEAD(signed_up) OVER (PARTITION BY email ORDER BY signed_up)) - julianday(signed_up) AS days_until_next
FROM signups
ORDER BY email, signed_up;
| signed_up | next_signup | days_until_next | |
|---|---|---|---|
| [email protected] | 2024-01-03 | 2024-01-09 | 6 |
| [email protected] | 2024-01-09 | 2024-02-01 | 23 |
| [email protected] | 2024-02-01 | NULL | NULL |
| [email protected] | 2024-01-04 | 2024-01-15 | 11 |
| [email protected] | 2024-01-15 | NULL | NULL |
| [email protected] | 2024-01-10 | NULL | NULL |
| [email protected] | 2024-01-11 | NULL | NULL |
| [email protected] | 2024-01-20 | NULL | NULL |
Common mistakes
- Forgetting
ORDER BYinsideOVER, which makes “previous” meaningless. - Not handling the first or last row. Pass a default, like
LAG(x, 1, 0), or useCOALESCE. - Missing
PARTITION BYwhen comparing within groups, so values leak between customers or products.
Practice LAG and LEAD interactively
Write real queries in your browser and get instant feedback in the lesson “Running totals, LAG and LEAD” (Unit 8). New learners can start free from the first lesson.
Frequently asked questions
Can LAG look back more than one row?
Yes, the second argument is the offset: LAG(sales, 7) compares with a week earlier in daily data.
How do I calculate a running total?
Use SUM(x) OVER (ORDER BY date). See window functions.