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;
Result on the SQL Café sample data (6 rows)
ordered_onsoldprev_daychange
2024-07-013NULLNULL
2024-07-0223-1
2024-07-03422
2024-07-0424-2
2024-07-05321
2024-07-0613-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;
Result on the Acme Co. (company data) sample data (8 rows)
emailsigned_upnext_signupdays_until_next
[email protected]2024-01-032024-01-096
[email protected]2024-01-092024-02-0123
[email protected]2024-02-01NULLNULL
[email protected]2024-01-042024-01-1511
[email protected]2024-01-15NULLNULL
[email protected]2024-01-10NULLNULL
[email protected]2024-01-11NULLNULL
[email protected]2024-01-20NULLNULL

Common mistakes

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.

Related SQL tutorials