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_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

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:

PartWhat it doesIf you leave it out
LAG(expression, offset, default)value from the row offset rows earlieroffset 1, default NULL
LEAD(expression, offset, default)value from the row offset rows lateroffset 1, default NULL
OVER (PARTITION BY …)only look within the same groupthe whole result
OVER (… ORDER BY …)defines what earlier and later meanallowed 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;
monthordersprev_monthnext_month
2026-013NULL3
2026-02333
2026-03332
2026-04232
2026-05225
2026-0652NULL

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_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.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_idorder_idorder_dateprevious_order
110012026-01-08NULL
110062026-02-252026-01-08
110152026-06-102026-02-25
410022026-01-12NULL
410172026-06-132026-01-12
710042026-02-03NULL
710142026-06-022026-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_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

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:

DatabaseLAG and LEADIGNORE NULLSDays between two dates
MySQLsince 8.0parsed, but raises an errorDATEDIFF(order_date, previous_order)
PostgreSQLyesnot implementedorder_date - previous_order (date type)
SQL Serversince 2012, ORDER BY inside OVER is requiredsince SQL Server 2022DATEDIFF(day, previous_order, order_date)
SQLite (these exercises)since 3.25.0not in the documented syntaxjulianday(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.

Up next: pivot with CASE WHEN

Revenue by category and month side by side, like a pivot table: with SUM and CASE WHEN you turn rows into columns.

Practice pivoting in SQL

Write to us

Choose language

Select your preferred language