SQL LAG and LEAD
What you will learn
- How
LAGreads the previous row andLEADthe next - How to compute a change from the last row
- How to set an offset and a default
- How to compare rows inside a group
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Run the cells from top to bottom.
1. The previous row
LAG(column) returns the value of the row before the current one, in the order of the window. The first row has no previous row, so it gets NULL:
WITH monthly AS (
SELECT SUBSTR(order_date, 1, 7) AS month, COUNT(*) AS orders
FROM orders GROUP BY SUBSTR(order_date, 1, 7)
)
SELECT month, orders,
LAG(orders) OVER (ORDER BY month) AS previous_month
FROM monthly
ORDER BY month
LIMIT 5;
month orders previous_month
------- ------ --------------
2024-01 17 NULL
2024-02 18 17
2024-03 27 18
2024-04 24 27
2024-05 43 24
(5 rows)
WITH monthly AS (
SELECT SUBSTR(txn_date, 1, 7) AS month, COUNT(*) AS txns
FROM transactions GROUP BY SUBSTR(txn_date, 1, 7)
)
SELECT month, txns,
LAG(txns) OVER (ORDER BY month) AS previous_month
FROM monthly
ORDER BY month
LIMIT 5;
month txns previous_month
------- ---- --------------
2018-02 2 NULL
2018-03 5 2
2018-04 6 5
2018-05 7 6
2018-06 11 7
(5 rows)
WITH monthly AS (
SELECT SUBSTR(class_date, 1, 7) AS month, COUNT(*) AS records
FROM attendance GROUP BY SUBSTR(class_date, 1, 7)
)
SELECT month, records,
LAG(records) OVER (ORDER BY month) AS previous_month
FROM monthly
ORDER BY month
LIMIT 5;
month records previous_month
------- ------- --------------
2025-02 1596 NULL
2025-03 798 1596
2025-08 630 798
2025-09 1260 630
2026-02 1152 1260
(5 rows)
2. Change from the last row
Subtract the previous value to get the change, and divide for a percentage:
WITH monthly AS (
SELECT SUBSTR(order_date, 1, 7) AS month, COUNT(*) AS orders
FROM orders GROUP BY SUBSTR(order_date, 1, 7)
)
SELECT month, orders,
orders - LAG(orders) OVER (ORDER BY month) AS change,
ROUND(100.0 * (orders - LAG(orders) OVER (ORDER BY month)) / LAG(orders) OVER (ORDER BY month), 1) AS change_percent
FROM monthly
ORDER BY month
LIMIT 5;
month orders change change_percent
------- ------ ------ --------------
2024-01 17 NULL NULL
2024-02 18 1 5.9
2024-03 27 9 50.0
2024-04 24 -3 -11.1
2024-05 43 19 79.2
(5 rows)
WITH monthly AS (
SELECT SUBSTR(txn_date, 1, 7) AS month, COUNT(*) AS txns
FROM transactions GROUP BY SUBSTR(txn_date, 1, 7)
)
SELECT month, txns,
txns - LAG(txns) OVER (ORDER BY month) AS change,
ROUND(100.0 * (txns - LAG(txns) OVER (ORDER BY month)) / LAG(txns) OVER (ORDER BY month), 1) AS change_percent
FROM monthly
ORDER BY month
LIMIT 5;
month txns change change_percent
------- ---- ------ --------------
2018-02 2 NULL NULL
2018-03 5 3 150.0
2018-04 6 1 20.0
2018-05 7 1 16.7
2018-06 11 4 57.1
(5 rows)
WITH monthly AS (
SELECT SUBSTR(class_date, 1, 7) AS month, COUNT(*) AS records
FROM attendance GROUP BY SUBSTR(class_date, 1, 7)
)
SELECT month, records,
records - LAG(records) OVER (ORDER BY month) AS change,
ROUND(100.0 * (records - LAG(records) OVER (ORDER BY month)) / LAG(records) OVER (ORDER BY month), 1) AS change_percent
FROM monthly
ORDER BY month
LIMIT 5;
month records change change_percent
------- ------- ------ --------------
2025-02 1596 NULL NULL
2025-03 798 -798 -50.0
2025-08 630 -168 -21.1
2025-09 1260 630 100.0
2026-02 1152 -108 -8.6
(5 rows)
The first row's change is NULL, because there is no previous month. That is correct, not a bug.
3. LEAD: the next row
LEAD(column) is the same but looks forward:
SELECT product_id, price,
LEAD(price) OVER (ORDER BY product_id) AS next_price
FROM products
ORDER BY product_id
LIMIT 5;
product_id price next_price
---------- ----- ----------
1 6.6 44.1
2 44.1 29.5
3 29.5 5.4
4 5.4 26.4
5 26.4 79.0
(5 rows)
SELECT account_id, balance_cents,
LEAD(balance_cents) OVER (ORDER BY account_id) AS next_balance
FROM accounts
ORDER BY account_id
LIMIT 5;
account_id balance_cents next_balance
---------- ------------- ------------
1 192400 52078
2 52078 62780
3 62780 99900
4 99900 153100
5 153100 218400
(5 rows)
SELECT course_id, credits,
LEAD(credits) OVER (ORDER BY course_id) AS next_credits
FROM courses
ORDER BY course_id
LIMIT 5;
course_id credits next_credits
--------- ------- ------------
1 4 3
2 3 4
3 4 4
4 4 4
5 4 4
(5 rows)
The last row has no next row, so it shows NULL.
4. Offset and default
LAG(column, n, default): look back n rows (default 1), and use default instead of NULL when there is no such row:
CREATE TABLE lib_temps (day INTEGER, temp INTEGER);
INSERT INTO lib_temps VALUES (1, 20), (2, 22), (3, 19), (4, 25), (5, 24);
SELECT day, temp,
LAG(temp, 1, 0) OVER (ORDER BY day) AS one_day_ago,
LAG(temp, 2) OVER (ORDER BY day) AS two_days_ago,
LEAD(temp, 1, -1) OVER (ORDER BY day) AS next_day
FROM lib_temps ORDER BY day;
day temp one_day_ago two_days_ago next_day
--- ---- ----------- ------------ --------
1 20 0 NULL 22
2 22 20 NULL 19
3 19 22 20 25
4 25 19 22 24
5 24 25 19 -1
(5 rows)
CREATE TABLE lib_temps (day INTEGER, temp INTEGER);
INSERT INTO lib_temps VALUES (1, 20), (2, 22), (3, 19), (4, 25), (5, 24);
SELECT day, temp,
LAG(temp, 1, 0) OVER (ORDER BY day) AS one_day_ago,
LAG(temp, 2) OVER (ORDER BY day) AS two_days_ago,
LEAD(temp, 1, -1) OVER (ORDER BY day) AS next_day
FROM lib_temps ORDER BY day;
day temp one_day_ago two_days_ago next_day
--- ---- ----------- ------------ --------
1 20 0 NULL 22
2 22 20 NULL 19
3 19 22 20 25
4 25 19 22 24
5 24 25 19 -1
(5 rows)
CREATE TABLE lib_temps (day INTEGER, temp INTEGER);
INSERT INTO lib_temps VALUES (1, 20), (2, 22), (3, 19), (4, 25), (5, 24);
SELECT day, temp,
LAG(temp, 1, 0) OVER (ORDER BY day) AS one_day_ago,
LAG(temp, 2) OVER (ORDER BY day) AS two_days_ago,
LEAD(temp, 1, -1) OVER (ORDER BY day) AS next_day
FROM lib_temps ORDER BY day;
day temp one_day_ago two_days_ago next_day
--- ---- ----------- ------------ --------
1 20 0 NULL 22
2 22 20 NULL 19
3 19 22 20 25
4 25 19 22 24
5 24 25 19 -1
(5 rows)
5. Time between events
With dates, LAG finds the gap since the previous event. JULIANDAY turns an ISO date into a day number (lesson 1.7):
Days between a customer's consecutive orders:
SELECT customer_id, order_id, order_date,
CAST(JULIANDAY(order_date) - JULIANDAY(LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date, order_id)) AS INTEGER) AS days_since_previous
FROM orders
WHERE customer_id <= 3
ORDER BY customer_id, order_date, order_id
LIMIT 6;
customer_id order_id order_date days_since_previous
----------- -------- ---------- -------------------
1 135 2025-10-01 NULL
1 289 2025-10-01 0
1 328 2025-10-01 0
1 554 2025-10-01 0
1 952 2025-10-01 0
1 1070 2025-10-01 0
(6 rows)
Days between an account's consecutive transactions:
SELECT account_id, txn_id, txn_date,
CAST(JULIANDAY(txn_date) - JULIANDAY(LAG(txn_date) OVER (PARTITION BY account_id ORDER BY txn_date, txn_id)) AS INTEGER) AS days_since_previous
FROM transactions
WHERE account_id <= 3
ORDER BY account_id, txn_date, txn_id
LIMIT 6;
account_id txn_id txn_date days_since_previous
---------- ------ ---------- -------------------
1 4704 2025-05-27 NULL
1 4713 2025-05-28 1
1 4820 2025-06-23 26
1 4894 2025-07-10 17
1 5059 2025-08-17 38
1 5172 2025-09-08 22
(6 rows)
Days between a student's consecutive enrollments:
SELECT student_id, section_id, enrolled_on,
CAST(JULIANDAY(enrolled_on) - JULIANDAY(LAG(enrolled_on) OVER (PARTITION BY student_id ORDER BY enrolled_on, section_id)) AS INTEGER) AS days_since_previous
FROM enrollments
WHERE student_id <= 3
ORDER BY student_id, enrolled_on, section_id
LIMIT 6;
student_id section_id enrolled_on days_since_previous
---------- ---------- ----------- -------------------
1 30 2025-01-14 NULL
1 41 2025-01-17 3
1 19 2026-01-18 366
2 32 2025-01-17 NULL
2 6 2025-08-05 200
2 9 2025-08-09 4
(6 rows)
PARTITION BY makes sure the "previous row" belongs to the same customer, account or student; each group's first row gets NULL.
6. Order matters
LAG and LEAD depend completely on the ORDER BY inside OVER. Add a tie-breaker (like order_id) or two events on the same day can swap places. Rows hidden by WHERE do not count: the previous row is the previous remaining row.
Worked example: find big jumps
| Step | Do |
|---|---|
| 1 | build the series: one row per month, with the total |
| 2 | add total - LAG(total) OVER (ORDER BY month) as change |
| 3 | put it in a CTE |
| 4 | keep rows where ABS(change) is large |
A window result cannot be filtered in its own SELECT, so the CTE is needed. The series is made up.
Common mistakes
- No
ORDER BYinOVER: "previous" has no meaning. - No
PARTITION BYwhen the data has groups, so rows mix. - Dividing by
LAGwhen it isNULLor zero. - Forgetting the first row is
NULL. - No tie-breaker in the order.
Key takeaways
LAG(x)is the previous row's value,LEAD(x)the next; the edge rows getNULLor your default.LAG(x, n, default)looksnrows away.- Subtract for a change; use
JULIANDAYfor days between dates. - Use
PARTITION BYto stay inside a group, and a tie-breaker in the order.
Practice
1. What does LAG(price) return for the first row?
Show answer
NULL, because there is no previous row (unless you give a default).
2. Write the change from the previous month.
Show answer
total - LAG(total) OVER (ORDER BY month)
3. What does LAG(x, 2, 0) mean?
Show answer
The value two rows back, or 0 when there is no such row.
4. Why PARTITION BY customer_id for days between orders?
Show answer
So the previous row is always the same customer's earlier order.
5. What is the difference between LAG and LEAD?
Show answer
LAG looks at earlier rows, LEAD at later rows.
6. Why must you filter a LAG result in an outer query?
Show answer
Window functions are not allowed in WHERE, so wrap the query in a CTE or subquery.