Skip to content
Silver 4 min read · Window 3 practice problems ↓

lag / lead

"How much did the price change since yesterday?", "how long since this user's last visit?" Both need a value from the row before or after. lag and lead fetch it. This lesson shows how, what happens at the edges, and how they lead to streak and gap questions.

Step 1 · PySpark functions · Silver · Window functions, lesson 2 of 2

Read first: row_number / rank (skip if you know it)

In plain words first

Standing in a queue, you can glance at the person in front of you and the person behind. lag is the glance forward to the previous row, lead the glance back to the next one. The first person has nobody in front, so their glance finds nothing (nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →), unless you give a default.

What it does

Inside each window partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more →, ordered by the window's order, lag("close") gives the previous row's close and lead("close") the next row's. They need an ordered window; a framewindow frame: The rows around the current one that a window function looks at, such as "the previous 6 rows" or "the last 7 days". Learn more → clause does not apply to them.

Step by step

prices (ACME)

dayclose
03-03100
03-04104
03-05101
03-06108

Output

daycloseprevchange
03-03100nullnull
03-041041004
03-05101104-3
03-061081017

The first day has no previous row, so prev is null and so is the change computed from it.

Run the example

PySparkSpark SQL

Input: prices

tickerdayclose
ACME2025-03-03100
ACME2025-03-04104
ACME2025-03-05101
ACME2025-03-06108
BOLT2025-03-0350
BOLT2025-03-0449
from pyspark.sql import functions as F
from pyspark.sql.window import Window

w = Window.partitionBy("ticker").orderBy("day")
result = (prices
    .withColumn("prev", F.lag("close").over(w))
    .withColumn("change", F.col("close") - F.col("prev"))
    .withColumn("next_close", F.lead("close").over(w)))
SELECT *,
       LAG(close)  OVER w           AS prev,
       close - LAG(close) OVER w    AS change,
       LEAD(close) OVER w           AS next_close
FROM prices
WINDOW w AS (PARTITION BY ticker ORDER BY day)

Offset and default

CallReturns
F.lag("close")Previous row, or null on the first row
F.lag("close", 2)Two rows back
F.lag("close", 1, 0.0)Previous row, or 0.0 when there is none
F.lead("close")Next row, or null on the last row

The default only fills the edges, where no row exists. If the previous row exists and its value is null, lag returns that null.

Gaps between events

With dates, lag lets you measure the time since the previous event: F.datediff("day", F.lag("day").over(w)). A gap above a threshold starts a new session, which is the basis of sessionisation.

Streaks: gaps and islands

To find runs of consecutive days, compare each row with the previous one and start a new group whenever the run breaks. A running sum of those break flags numbers the groups:

  1. 1
    is_break = 1 when the gap to the previous day is not exactly 1, else 0 (use lag).
  2. 2
    streak_id = sum(is_break) over the window ordered by day, from the start up to the current row.
  3. 3
    Group by streak_id to get each streak's start, end and length.

The same shape solves "consecutive months of growth", "login streaks" and "status unchanged since". Interviewers love it because it combines lag with a running total.

Under the hood Optional deep dive

lag and lead run in the same shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more →-and-sort as other window functionswindow function: A function that computes a value for each row from a group of related rows (its window), without collapsing them like groupBy does. Learn more → over the same spec. After sorting, Spark keeps a small buffer of rows, so the offset itself is nearly free. The cost is the shuffle, and the risk is skewskew: When one key has far more rows than the others, so one task does most of the work while the rest wait. Learn more →: one ticker with most of the rows makes one slow tasktask: The work for one partition in one stage, run on one CPU core. Learn more →.

Common mistakes

  • Ordering by a string date in the wrong format — "3/10/2025" sorts before "3/9/2025" as text. Order by a real date or an ISO yyyy-MM-dd string.
  • Forgetting partitionBy — Without it, the first row of ticker B reads the last row of ticker A as its previous value.
  • Assuming the default replaces nulls — It only applies where there is no row at the offset.

Key takeaways

  • lag reads a previous row, lead a following one, within each ordered partition.
  • At the partition edges they return null or the default you pass.
  • Day-over-day change is col - lag(col).
  • lag plus a running sum of break flags finds streaks (gaps and islands).

Interview prep

THE QUESTION

"Find users who logged in on three consecutive days."

Deduplicate to one row per user per day, then compare each date with lag(day, 2) over the user window: if it is exactly 2 days earlier, the user has a three-day run ending today. Or use the gaps-and-islands running sum for arbitrary lengths. Mention deduplicating first: two logins on the same day break the logic.

Avoid: lagging over raw login rows. With several logins per day, lag(2) compares within the same day; deduplicate to one row per user per day first.

Follow-ups · answer out loud, then open

Follow-up"What does lag return for the first row of each partition, and how do you change it?"
null, because there is no previous row. Pass a default as the third argument, F.lag("x", 1, 0), or coalesce afterwards.
Scenario"Compute session ids: a new session starts after 30 minutes of inactivity."
Use lag to get the previous event time per user, flag a new session when the gap exceeds 30 minutes (or there is no previous event), then take a running sum of the flag over the user window ordered by time. The running sum is the session number.
Trap"lag works without orderBy in the window."
It needs an ordered window: Spark raises an error if the window has no ORDER BY. "Previous row" only means something with an order.

Check yourself

3 questions

What does F.lag("v", 1, 0) return when the previous row exists but its v is null?

Show the answer

null. The default is used only when there is no row at the offset. An existing null is returned as null.

Why must the lag window be partitioned by ticker?

Show the answer

Otherwise the first row of one ticker reads the last row of another. Without partitioning, rows from different tickers are neighbours in one ordered sequence.

Which pattern finds runs of consecutive days?

Show the answer

lag to flag breaks, then a running sum of the flags. Flags mark where a run breaks; their running sum gives every run its own id.

Practise this

Problems that use lag / lead, graded on hidden tests

Keep going

Up next · new module: Smarter aggregates · 4 min read
max_by / min_by
Return the value from the row where another column is largest or smallest, in one aggregate.

Related lessons

Previous: row_number / rank

Primary sources: functions.lag · functions.lead