LAG & LEAD Analytical Functions
Compare current rows to previous/next periods for deltas, churn, and session logic.
In plain words
LAG looks at the previous row and LEAD looks at the next row, so you can compare each event with the one before or after it.
Think of it like…
Reading a diary: LAG is flipping back one entry to see what you wrote yesterday; LEAD is peeking at tomorrow's page. Yesterday's page is legitimate context; tomorrow's page is cheating if you're trying to predict tomorrow.
Where you’ve seen it
An e-commerce model predicts whether a customer will purchase again within 30 days of each order. Feature: days_since_prev_order = order_date - LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date, order_id). Label: CASE WHEN LEAD(order_date) OVER (PARTITION BY customer_id ORDER BY order_date, order_id) <= order_date + 30 THEN 1 ELSE 0 END. The last order of every customer has a NULL LEAD, so those rows are labelled 0 only if the observation window (data end date minus 30 days) covers them, and otherwise excluded as unobserved.
Words you’ll hear
- LAG
- Value from an earlier row in the partition order; valid for features.
- LEAD
- Value from a later row; valid for labels and retrospective analysis only.
- Offset and default
- LAG(col, 2, 0) looks 2 rows back and returns 0 when there is none.
- Right censoring
- Recent rows whose outcome window isn't complete yet and must not be labelled 0.
Visual diagram
Theory & deep dive
Using LAG and LEAD
Both functions need a window ORDER BY and usually a PARTITION BY (per customer, per sensor). LAG(amount) OVER (PARTITION BY customer_id ORDER BY order_date) is the previous order's amount; amount - LAG(amount) is the change, and amount / NULLIF(LAG(amount), 0) - 1 is the percentage change, guarding against division by zero. Subtracting dates gives gaps: order_date - LAG(order_date) in PostgreSQL returns days; use DATEDIFF or DATE_DIFF in other dialects. An offset of 7 on daily data gives the same weekday last week.
Session and streak logic: flag a new session when the gap exceeds a threshold (CASE WHEN ts - LAG(ts) > interval '30 minutes' OR LAG(ts) IS NULL THEN 1 ELSE 0 END), then take a running SUM of the flag to number sessions. Always add a unique tie-breaker to the ORDER BY so events with identical timestamps have a stable order.
SUM(new_session) OVER (PARTITION BY user_id ORDER BY ts, event_id ROWS UNBOUNDED PRECEDING) AS session_id where new_session is 1 when the gap since the previous event exceeds 30 minutes or there is no previous event.
Labels, censoring and leakage
Features must use only information available at the prediction time, so use LAG (or aggregates over earlier rows). Labels describe what happens afterwards, so LEAD (or aggregates over later rows) is appropriate there, and only there. Mixing them up is the most common route to a model with suspiciously perfect validation scores. Keep feature and label logic in clearly separated CTEs and write the prediction timestamp next to each.
Censoring: a customer whose last order was 10 days before the end of your data hasn't had 30 days to reorder, so a NULL LEAD doesn't mean "didn't reorder". Set an observation cut-off (data_end - 30 days) and exclude later rows from training, or label them unknown. Also split train and test by time, not randomly, since sequences from the same customer in both sets leak patterns. In pandas, groupby(...).shift(1) is LAG and shift(-1) is LEAD; double-check the sign.
WHERE order_date <= DATE '2026-11-30' - 30 keeps only orders whose 30-day outcome window is fully inside the data (data ends 2026-11-30), so a NULL LEAD in the remaining rows genuinely means no follow-up order.
How it works, step by step
Step 1 of 41. Define the prediction point
Decide when predictions are made (after each order) and which information is available then.
- Features
- past only
When to use it & trade-offs
What it is
LAG(col, n, default) returns the value from n rows before the current row within its partition and ordering; LEAD(col, n, default) returns the value from n rows after. They turn a table of events into comparisons across time without a self join: day-over-day change (amount - LAG(amount)), days since the previous order (order_date - LAG(order_date)), session breaks (a gap over 30 minutes), and labels such as "will this customer order again within 30 days?" (a LEAD over their future orders). The first and last rows of each partition have no neighbour and return NULL unless you supply a default.
Why it matters: Sequence features (recency, gaps, deltas, streaks) are among the most predictive in churn, fraud and engagement models, and LAG/LEAD compute them in one pass over the data. The central hazard is direction: LAG looks backwards (a valid feature), LEAD looks forwards (only valid for labels or analysis of the past). Using LEAD in a feature column is a classic way to leak the future into a model.
When to reach for it
- Recency, gap and change features
- Sessionisation and streaks
- Next-event labels for supervised models
When to avoid or be careful
- LEAD in feature columns
- Labelling unobserved recent rows as negatives
- Random train/test splits on sequential data
Row-to-row comparison techniques
Strengths: One pass; clear intent; no join.
Watch out: Only fixed offsets; NULLs at edges.
Strengths: Flexible conditions.
Watch out: Heavier; can multiply rows.
Strengths: Quick and flexible.
Watch out: Doesn't scale to warehouse-sized data.
Interview signals & numbers to know
When this topic comes up
- “Days since last purchase”
- “Validation score is too good to be true”
- “Define the churn label”
- Sessionisation
- Time-based splits
Benchmarks & rules of thumb
- 30 minutes
- a common session gap threshold
- 30 days
- the label window in the example
- −1 / +1
- shift offsets in pandas for LAG / LEAD
Common mistakes & follow-ups
Common interview mistakes
- Using LEAD for a feature such as "next order amount" and leaking the future.
- Treating the NULL LEAD of a recent order as "won't return".
- Randomly splitting rows so a customer's earlier orders train the model that predicts their later ones in the test set.
Likely interviewer follow-ups
- How would you build a next-30-days purchase label?
- What is right-censoring in this context?
- How do you sessionise click events in SQL?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply LAG & LEAD Analytical Functions with data science interview Q&A and hands-on practice.