LAG function in SQL: compare a row with the one before (and after)
How much did revenue grow on last month? How many days since this customer last ordered? To answer that, a row needs a value from the row before it. LAG fetches exactly that, and LEAD fetches the value from the row after.
In short: LAG(revenue) OVER (ORDER BY month) returns the previous row's revenue on every row, and LEAD(revenue) OVER (ORDER BY month) returns the next row's. Where no such row exists you get NULL. Add PARTITION BY customer_id and LAG only looks back within the same customer.
What you should know first: window functions with OVER from the running total lesson, intermediate results with WITH (CTEs) and working with dates.
Try it now
In a spreadsheet you'd compare with the row above by pointing at the cell one row up. A SQL table has no "row above" until you say what order the rows are in, and that's what goes inside OVER.
Task Sales wants to see how closely orders follow one another. For each order show order_id, order_date and previous_order: the date of the order that came just before it, across all customers. The very first order has no predecessor, so that field stays empty.
orders 18 rows, 5 columns
| order_id | customer_id | order_date | status | employee_id |
|---|---|---|---|---|
| 1001 | 1 | 2026-01-08 | delivered | 3 |
| 1002 | 4 | 2026-01-12 | delivered | 4 |
| 1003 | 3 | 2026-01-20 | delivered | 3 |
| 1004 | 7 | 2026-02-03 | delivered | 4 |
| 1005 | 2 | 2026-02-11 | cancelled | 8 |
| 1006 | 1 | 2026-02-25 | delivered | 3 |
| 1007 | 10 | 2026-03-04 | delivered | 2 |
| 1008 | 5 | 2026-03-17 | delivered | 4 |
| 1009 | 8 | 2026-03-30 | delivered | 3 |
| 1010 | 6 | 2026-04-07 | delivered | 8 |
| 1011 | 12 | 2026-04-22 | delivered | 4 |
| 1012 | 3 | 2026-05-06 | delivered | 3 |
| 1013 | 9 | 2026-05-19 | cancelled | 8 |
| 1014 | 7 | 2026-06-02 | shipped | 4 |
| 1015 | 1 | 2026-06-10 | shipped | 3 |
| 1016 | 11 | 2026-06-12 | open | NULL |
| 1017 | 4 | 2026-06-13 | open | NULL |
| 1018 | 10 | 2026-06-14 | open | NULL |
How LAG and LEAD work
LAG and LEAD are window functions, just like SUM with OVER. They don't add anything up, though; they fetch a value from another row. Which row that is depends on the ORDER BY inside the brackets after OVER:
| Part | What it does | If you leave it out |
|---|---|---|
LAG(expression, offset, default) | value from the row offset rows earlier | offset 1, default NULL |
LEAD(expression, offset, default) | value from the row offset rows later | offset 1, default NULL |
OVER (PARTITION BY …) | only look within the same group | the whole result |
OVER (… ORDER BY …) | defines what earlier and later mean | allowed in SQLite, but with no fixed order |
Here's an example with the number of orders per month. The WITH block does the counting, then LAG and LEAD pull in the neighboring months:
WITH m AS (
SELECT strftime('%Y-%m', order_date) AS month, COUNT(*) AS orders
FROM orders
GROUP BY month
)
SELECT month, orders,
LAG(orders) OVER (ORDER BY month) AS prev_month,
LEAD(orders) OVER (ORDER BY month) AS next_month
FROM m
ORDER BY month;
| month | orders | prev_month | next_month |
|---|---|---|---|
| 2026-01 | 3 | NULL | 3 |
| 2026-02 | 3 | 3 | 3 |
| 2026-03 | 3 | 3 | 2 |
| 2026-04 | 2 | 3 | 2 |
| 2026-05 | 2 | 2 | 5 |
| 2026-06 | 5 | 2 | NULL |
January has no previous month and June has no next one, so those cells are NULL. LAG never makes up a value where there's no row.
Month-over-month change as a percentage
Once last month's figure sits on the same row, the rest is arithmetic. The difference is new - old, and the percentage change is 100.0 * (new - old) / old. Using the WITH block from above:
SELECT month, orders,
orders - LAG(orders) OVER (ORDER BY month) AS difference,
ROUND(100.0 * (orders - LAG(orders) OVER (ORDER BY month))
/ LAG(orders) OVER (ORDER BY month), 1) AS change_pct
FROM m
ORDER BY month;
April shows a difference of -1 and a change of -33.3 percent; June shows +3 and 150 percent. The 100.0 matters here: COUNT returns whole numbers, and with a plain 100 SQLite would do integer division and give you -33 for April. Your turn, with revenue instead of order counts:
Task For the monthly report: for each month show month (as text YYYY-MM), revenue excluding cancelled orders, prev_month with the previous month's revenue, and change_pct with the change from the previous month as a percentage, rounded to one decimal place. Revenue means quantity times unit_price from order_items. For the first month, previous revenue and change stay empty.
orders 18 rows, 5 columns
| order_id | customer_id | order_date | status | employee_id |
|---|---|---|---|---|
| 1001 | 1 | 2026-01-08 | delivered | 3 |
| 1002 | 4 | 2026-01-12 | delivered | 4 |
| 1003 | 3 | 2026-01-20 | delivered | 3 |
| 1004 | 7 | 2026-02-03 | delivered | 4 |
| 1005 | 2 | 2026-02-11 | cancelled | 8 |
| 1006 | 1 | 2026-02-25 | delivered | 3 |
| 1007 | 10 | 2026-03-04 | delivered | 2 |
| 1008 | 5 | 2026-03-17 | delivered | 4 |
| 1009 | 8 | 2026-03-30 | delivered | 3 |
| 1010 | 6 | 2026-04-07 | delivered | 8 |
| 1011 | 12 | 2026-04-22 | delivered | 4 |
| 1012 | 3 | 2026-05-06 | delivered | 3 |
| 1013 | 9 | 2026-05-19 | cancelled | 8 |
| 1014 | 7 | 2026-06-02 | shipped | 4 |
| 1015 | 1 | 2026-06-10 | shipped | 3 |
| 1016 | 11 | 2026-06-12 | open | NULL |
| 1017 | 4 | 2026-06-13 | open | NULL |
| 1018 | 10 | 2026-06-14 | open | NULL |
order_items 38 rows, 4 columns
| order_id | product_id | quantity | unit_price |
|---|---|---|---|
| 1001 | 1 | 40 | 4.79 |
| 1001 | 3 | 25 | 2.79 |
| 1001 | 6 | 4 | 24.9 |
| 1002 | 2 | 2 | 3.49 |
| 1002 | 10 | 3 | 5.49 |
| 1003 | 1 | 60 | 4.69 |
| 1003 | 11 | 6 | 84.9 |
| 1003 | 3 | 50 | 2.59 |
| 1004 | 4 | 3 | 179 |
| 1004 | 9 | 3 | 269 |
| 1005 | 5 | 1 | 449 |
| 1006 | 1 | 30 | 4.79 |
| 1006 | 7 | 10 | 6.99 |
| 1007 | 8 | 2 | 219 |
| 1007 | 11 | 4 | 89.9 |
| 1007 | 1 | 20 | 4.99 |
| 1008 | 4 | 6 | 175 |
| 1008 | 2 | 5 | 3.49 |
| 1009 | 10 | 120 | 4.99 |
| 1009 | 2 | 40 | 3.19 |
| 1009 | 9 | 2 | 279 |
| 1010 | 7 | 2 | 6.99 |
| 1010 | 2 | 1 | 3.49 |
| 1011 | 12 | 1 | 129 |
| 1011 | 1 | 10 | 4.99 |
| 1011 | 3 | 12 | 2.79 |
| 1012 | 6 | 8 | 23.9 |
| 1012 | 1 | 40 | 4.69 |
| 1013 | 9 | 1 | 279 |
| 1014 | 5 | 2 | 439 |
| 1014 | 4 | 2 | 179 |
| 1015 | 1 | 50 | 4.79 |
| 1015 | 11 | 2 | 89.9 |
| 1016 | 10 | 4 | 5.49 |
| 1017 | 2 | 3 | 3.49 |
| 1017 | 7 | 2 | 6.99 |
| 1018 | 1 | 80 | 4.79 |
| 1018 | 6 | 10 | 24.9 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Offset and default value
The second argument says how many rows LAG goes back. LAG(revenue, 2) fetches the value from two rows earlier, which on monthly rows means two months back. The third argument replaces NULL when there's no such row: LAG(orders, 1, 0) shows 0 for January instead of NULL. Think about whether 0 is actually true, though. For a percentage, NULL is the honest answer, since you can't divide by 0.
Watch out for gaps: LAG steps back through rows, not calendar months. If a month with no sales has no row at all, LAG quietly compares with the month before it. For month-over-month reports, check that every month really has a row.
Looking back per customer with PARTITION BY
To measure the gap between two orders from the same customer, LAG must not peek at other customers' orders. PARTITION BY customer_id splits the rows by customer, and ORDER BY order_date sorts them within each customer:
SELECT customer_id, order_id, order_date,
LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS previous_order
FROM orders
WHERE customer_id IN (1, 4, 7)
ORDER BY customer_id, order_date;
| customer_id | order_id | order_date | previous_order |
|---|---|---|---|
| 1 | 1001 | 2026-01-08 | NULL |
| 1 | 1006 | 2026-02-25 | 2026-01-08 |
| 1 | 1015 | 2026-06-10 | 2026-02-25 |
| 4 | 1002 | 2026-01-12 | NULL |
| 4 | 1017 | 2026-06-13 | 2026-01-12 |
| 7 | 1004 | 2026-02-03 | NULL |
| 7 | 1014 | 2026-06-02 | 2026-02-03 |
Each customer starts with NULL. In SQLite you get the days in between with julianday(order_date) - julianday(previous_order); from 2026-01-08 to 2026-02-25 that's 48. The next exercise adds a filter on top.
Task Customer service wants to know how long repeat customers wait between orders. Show every order placed by a customer who had already ordered before, with customer_id, order_id, order_date and days, the number of days since that customer's previous order. A customer's first order doesn't belong in the result.
orders 18 rows, 5 columns
| order_id | customer_id | order_date | status | employee_id |
|---|---|---|---|---|
| 1001 | 1 | 2026-01-08 | delivered | 3 |
| 1002 | 4 | 2026-01-12 | delivered | 4 |
| 1003 | 3 | 2026-01-20 | delivered | 3 |
| 1004 | 7 | 2026-02-03 | delivered | 4 |
| 1005 | 2 | 2026-02-11 | cancelled | 8 |
| 1006 | 1 | 2026-02-25 | delivered | 3 |
| 1007 | 10 | 2026-03-04 | delivered | 2 |
| 1008 | 5 | 2026-03-17 | delivered | 4 |
| 1009 | 8 | 2026-03-30 | delivered | 3 |
| 1010 | 6 | 2026-04-07 | delivered | 8 |
| 1011 | 12 | 2026-04-22 | delivered | 4 |
| 1012 | 3 | 2026-05-06 | delivered | 3 |
| 1013 | 9 | 2026-05-19 | cancelled | 8 |
| 1014 | 7 | 2026-06-02 | shipped | 4 |
| 1015 | 1 | 2026-06-10 | shipped | 3 |
| 1016 | 11 | 2026-06-12 | open | NULL |
| 1017 | 4 | 2026-06-13 | open | NULL |
| 1018 | 10 | 2026-06-14 | open | NULL |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Common mistakes
Leaving out OVER
SELECT order_id, order_date, LAG(order_date) FROM orders fails, because LAG only exists as a window function. The exercise says that window functions can't go in WHERE and that every window function needs OVER; the second part is the one that applies here. Add OVER (ORDER BY order_date).
No order inside OVER
LAG(order_date) OVER () is accepted by SQLite, but which row counts as the previous one is left to chance. With our data it may happen to work, and the exercise then says the result is right with this data but not with other data. The same happens if you order by order_id instead of the date.
LAG in WHERE
WHERE LAG(order_date) OVER (…) IS NOT NULL isn't allowed, and a column alias from AS isn't known in WHERE yet either. The exercise tells you that window functions like LAG can't go in WHERE. Calculate LAG in a WITH block and filter in the query after it.
Reusing your own column name right away
In Excel you're used to building on a helper column. In SQL, SELECT …, LAG(revenue) OVER (ORDER BY month) AS prev_month, 100 * (revenue - prev_month) / prev_month … doesn't work: prev_month isn't known yet in the same SELECT, and the exercise reports that there is no column "prev_month". Either write LAG out in full each time, or create prev_month in a second WITH block and do the maths in the query after it.
Date minus date
order_date - LAG(order_date) OVER (…) gives 0 everywhere in SQLite, because the dates are text and SQLite only reads the year at the front as a number. The exercise then says not all values match. For days you need julianday(order_date) - julianday(…).
Forgetting PARTITION BY
Without PARTITION BY customer_id you measure the gap to whichever order came before, from any customer. Almost every row then has a predecessor, and the exercise says "Your query returns 17 rows. Wanted: 6 rows."
Dividing by the wrong value
A change is measured against the old value: (new - old) / old. Divide by the new value and the percentages shift, so the exercise reports that not every value matches.
LAG and LEAD in MySQL, PostgreSQL, SQL Server and SQLite
The form LAG(expression, offset, default) OVER (PARTITION BY … ORDER BY …) is the same in all four, and so is LEAD. Where they differ:
| Database | LAG and LEAD | IGNORE NULLS | Days between two dates |
|---|---|---|---|
| MySQL | since 8.0 | parsed, but raises an error | DATEDIFF(order_date, previous_order) |
| PostgreSQL | yes | not implemented | order_date - previous_order (date type) |
| SQL Server | since 2012, ORDER BY inside OVER is required | since SQL Server 2022 | DATEDIFF(day, previous_order, order_date) |
| SQLite (these exercises) | since 3.25.0 | not in the documented syntax | julianday(order_date) - julianday(previous_order) |
IGNORE NULLS skips rows with NULL and fetches the most recent non-NULL value instead. Where it's missing, a subquery does the job. Sources: MySQL Reference Manual (What Is New in MySQL 8.0, Window Function Descriptions, Date and Time Functions), PostgreSQL documentation (Window Functions, Date/Time Functions and Operators), Microsoft Learn (LAG, DATEDIFF), sqlite.org (Window Functions).
FAQ
What's the difference between LAG and LEAD?
Only the direction. LAG looks back in the order set by OVER, LEAD looks ahead. LEAD(order_date) OVER (ORDER BY order_date) gives the same as LAG(order_date) OVER (ORDER BY order_date DESC). Use whichever reads more naturally.
How do I compare with the same month last year?
On monthly rows with no gaps, use LAG(revenue, 12) OVER (ORDER BY month). The first twelve months then get NULL. Our practice data only runs from January to June 2026, so there's no prior year yet.
Why is the first row NULL?
Because there's no row before it. LAG then returns NULL, or the default from the third argument. Any calculation with NULL is NULL too, which is why the change for the first month is empty.
Can I do this without LAG?
Yes, for example with a subquery that finds the latest earlier date for each row, or with a self join. Both are longer and harder to read. With LAG the intent is right there in the query.