Skip to content
Silver 6 min read · Windows 2 practice problems ↓

LAG and LEAD

Many questions compare a row with the row before it: how much did revenue change since yesterday, how many days since a customer's last order. LAG and LEAD put the previous or next row's value right next to the current one.

Foundations · SQL for data engineers · Silver · Window functions, lesson 2 of 3

Read first: Window functions: ranking and top N (skip if you know it)

In plain words first

Picture each customer's orders as a list, oldest first. For each order:

LAG: look back

The value from the row before this one in the list. The first order has nothing before it, so LAG gives NULLNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more →.

LEAD: look ahead

The value from the row after this one. The last order has nothing after it, so LEAD gives NULL.

Both are window functionswindow function: A function computed over a group of rows, written with OVER (...), that keeps every row instead of collapsing them like GROUP BY. Learn more →, so they need OVER (PARTITION BY ... ORDER BY ...). The ORDER BY is what defines "before" and "after", and it is required.

Spark SQL · The previous and next amount for each customer

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT customer_id, order_date, order_id, amount,
       lag(amount)  OVER (PARTITION BY customer_id ORDER BY order_date) AS prev_amount,
       lead(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS next_amount
FROM orders
WHERE customer_id IN (1, 2)
ORDER BY customer_id, order_date

Read Asha's three rows (customer 1): 420 has no previous order, 300 sees 420 before it, 180 sees 300 before it and nothing after. PARTITION BY keeps each customer separate: Ravi's first order does not look back at Asha's last one.

Time between events

Subtract the previous value from the current one and you have a change. With dates, datediff gives the days since the customer's previous order:

Spark SQL · Days since each customer's previous order

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT customer_id, order_id, order_date,
       datediff(
         order_date,
         lag(order_date) OVER (PARTITION BY customer_id ORDER BY order_date)
       ) AS days_since_last
FROM orders
ORDER BY customer_id, order_date

A customer's first order is NULL: there is no previous one. That NULL is honest. Replacing it with 0 would claim the customer ordered twice on the same day.

Offsets and defaults

LAG and LEAD take two optional arguments: how many rows to step (default 1) and what to return when there is no such row (default NULL).

CallReturns
lag(amount)The previous row's amount, or NULL on the first row
lag(amount, 2)The amount two rows back
lag(amount, 1, 0)The previous amount, or 0 when there is none
lead(amount)The next row's amount, or NULL on the last row
Spark SQL · Change from the previous order, counting from 0

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT customer_id, order_id, amount,
       amount - lag(amount, 1, 0) OVER (
         PARTITION BY customer_id ORDER BY order_date
       ) AS change
FROM orders
WHERE customer_id = 1
ORDER BY order_date

Use a default only when it means something. Here the first change is 420 (from nothing to 420), which suits "how much did spending grow". For "days since last order" a default of 0 would be wrong, as shown above.

Day-over-day change

To compare days, first make one row per day, then use LAG over those rows. A CTECTE: A common table expression: a named step of a query, written WITH name AS (...), that later steps use like a table. Learn more → (the WITH part, covered in its own lesson) holds the daily totals:

Spark SQL · Revenue and its change from the previous day

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
WITH daily AS (
  SELECT order_date, sum(amount) AS revenue
  FROM orders
  GROUP BY order_date
)
SELECT order_date, revenue,
       lag(revenue) OVER (ORDER BY order_date) AS prev_revenue,
       round(100.0 * (revenue - lag(revenue) OVER (ORDER BY order_date))
             / lag(revenue) OVER (ORDER BY order_date), 1) AS pct_change
FROM daily
ORDER BY order_date
The previous row is not always the previous day: There were no orders on 3 March, so the row for the 4th compares with the 2nd. LAG looks at the previous row, whatever its date. If the question is "compared with yesterday", fill in the missing days first with a date spinedate spine: A list of every day in a range, LEFT JOINed to data so that days with no rows still appear, usually with zeros. Learn more → (the dates lesson).

Filtering on LAG and LEAD

Like ranking, LAG and LEAD cannot be used in WHERE. Compute them in a subquerysubquery: A query inside another query, in brackets: in FROM as a table, or in WHERE with IN or EXISTS. Learn more → first. Which orders were followed by another order from the same customer within 2 days?

Spark SQL · Orders followed by another within 2 days

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT customer_id, order_id, order_date
FROM (
  SELECT *,
         lead(order_date) OVER (
           PARTITION BY customer_id ORDER BY order_date
         ) AS next_date
  FROM orders
)
WHERE datediff(next_date, order_date) <= 2
ORDER BY customer_id

For a last order, next_date is NULL, so the condition is NULL and WHERE drops the row, which is what we want here.

Common mistakes

  • Forgetting PARTITION BY — The first row of one customer looks back at the last row of another customer. Partition by the key you are comparing within.
  • Assuming the previous row is yesterday — LAG skips missing days silently. Fill the gaps with a date spine when the question is about calendar days.
  • Defaulting LAG to 0 by habit — A first row has no previous value. A default of 0 can turn "unknown" into a wrong number.
  • Ordering by a column with ties — Two orders on the same date can come in either order. Add a tie-breaker such as order_id.

Key takeaways

  • LAG reads the previous row in the window, LEAD the next one.
  • ORDER BY defines "previous"; PARTITION BY keeps groups apart.
  • The first row's LAG (and the last row's LEAD) is NULL unless you give a default.
  • lag(x, n, default): step n rows back, with a value for when there is none.
  • LAG works on rows, not dates: missing days need a date spine.

Interview prep

THE QUESTION

"For each day, show revenue and the percentage change from the previous day."

Aggregate to one row per day in a CTE, then lag(revenue) OVER (ORDER BY day) for the previous value and (revenue - prev) / prev for the change; the first day is NULL because there is no previous day. Then ask whether days with no sales exist: LAG looks at the previous row, not the previous calendar day, so I would join the daily totals to a calendar of all days first, with zero for missing days, or the change would compare non-adjacent days. Also guard the division when the previous day is 0.

Avoid: LAG over the raw daily totals without checking for missing days. On a day after a gap, "the previous day" is really two or three days earlier, and the percentage change is quietly wrong.

Follow-ups · answer out loud, then open

Follow-up"How would you find users whose next login came more than 7 days after the previous one?"
Compute lead(login_date) OVER (PARTITION BY user_id ORDER BY login_date) in a subquery, then filter datediff(next_login, login_date) > 7 outside. Each user's last login has a NULL next date and drops out, which is correct for "came back after a gap".
Scenario"Month-over-month revenue is needed per country, and some countries have months with no sales."
Aggregate to country and month, then cross join the list of countries with a month spine and LEFT JOIN the totals, with zero for missing months. Only then lag(revenue) OVER (PARTITION BY country ORDER BY month). Without the spine, LAG compares non-adjacent months.
Trap"Is lag(x) OVER (ORDER BY ts) the same as a self join on the previous timestamp?"
Same answer when timestamps are unique, but the self join needs a correlated "max earlier ts" lookup and grows badly; LAG reads each row once after one sort. With duplicate timestamps neither is well defined until you add a tie-breaker.

Check yourself

4 questions

What is lag(amount) on the first row of a partition?

Show the answer

NULL. There is no previous row, and the default default is NULL.

lag(amount, 2, 0) on the second row returns...

Show the answer

0. Two rows back does not exist, so the default 0 is returned.

Daily totals exist for 1, 2 and 4 March. What does LAG give on the 4th?

Show the answer

The total of the 2nd. LAG reads the previous row, whatever its date.

What happens without PARTITION BY customer_id when comparing each customer's orders?

Show the answer

The first order of each customer compares with another customer's order. Without a partition, the whole table is one list.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Window functions · lesson 3 of 3 · 7 min read
Running totals and window frames
Running totals, moving averages and percent of total, and the frame that decides which rows are added up.

Related lessons

Previous: Window functions: ranking and top N

Primary sources: Window functions (LAG, LEAD) · lag