Stop 08 · Window FunctionsTopics · 5/9

LAG and LEAD

Part of the SQL Roadmap

In short

"Did sales go up or down compared to last month?" is one of the most asked business questions. LAG and LEAD let a row peek at its neighbours, so this becomes a single, tidy query.

LAG reads a value from a previous row and LEAD from a following row in the window, which makes period-over-period comparisons easy.

The jaadu drives a small car on a highway, glancing into the rear-view mirror at one car behind while another car drives just ahead.

Think of it like this

Mirror and windscreen

Driving on the Mumbai-Pune expressway, you glance at the rear-view mirror to see the car behind you and look through the windscreen at the car ahead. LAG is the mirror: it reads the previous row. LEAD is the windscreen: it reads the next row. You stay in your own lane the whole time.

Watch it happen

Monthly revenue, one row per month

Jan ₹42,000
0
current
Feb ₹48,000
1
Mar ₹45,000
2
Apr ₹51,000
3

1/5Four months, ordered by month. That order is what 'previous' and 'next' mean.

The big ideas

What you need to know

LAG looks back

LAG(revenue) returns the value from the row before, in the order you set inside OVER.

LEAD looks ahead

LEAD(revenue) returns the value from the next row. Handy for 'days until next order'.

Offset and default

LAG(revenue, 12) reaches back 12 rows for year-on-year. LAG(revenue, 1, 0) returns 0 instead of NULL at the edge.

Partition to stay in lane

Add PARTITION BY city so Pune's January never compares with Delhi's December.

See it in code

Walk through the code

sql
1SELECT2  month,3  revenue,4  LAG(revenue)  OVER (ORDER BY month) AS prev_month,5  LEAD(revenue) OVER (ORDER BY month) AS next_month,6  revenue - LAG(revenue) OVER (ORDER BY month) AS change7FROM monthly_sales8WHERE city = 'Chennai'9ORDER BY month;

1/4Read revenue from the previous month. The first month gets NULL.

Each month's revenue next to the month before and after it. LAG and LEAD work the same way in PostgreSQL, MySQL 8+ and SQL Server.

Save yourself the pain

Common mistakes

Oops

Leaving ORDER BY out of the OVER clause.

Do this instead

Without ORDER BY, 'previous row' has no meaning. Always say which order the rows follow.

Oops

Assuming LAG gives last calendar month when a month is missing from the table.

Do this instead

LAG reads the previous row, not the previous month. Fill missing months first if gaps are possible.

Your mission

Up or down?

~20 min

Quick check

What does LAG(revenue, 1, 0) OVER (ORDER BY month) return on the very first month?

Go deeper

  1. 1Show each month's revenue next to the previous month's.
  2. 2Calculate days between a customer's consecutive orders.
  3. 3Use the default argument to replace the first row's NULL when it makes sense.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge