Offset Functions: LAG() & LEAD() (Accessing Previous & Next Rows)
Look backward and forward within a partition for deltas and comparisons.
In plain words
LAG looks at the row before; LEAD looks at the row after. You decide what "before" means with ORDER BY.
Think of it like…
Reading a diary: LAG is glancing back at yesterday's entry while you read today's; LEAD is peeking at tomorrow's.
Where you’ve seen it
Month-over-month revenue growth: SELECT month, revenue, revenue - LAG(revenue) OVER (ORDER BY month) AS change FROM monthly_revenue;. The first month's change is NULL because there's no previous row.
Words you’ll hear
- Offset
- How many rows back or ahead to look. The default is 1.
- Default value
- The optional third argument, returned when there's no such row (instead of NULL).
- PARTITION BY
- Restarts the look-back for each group, such as each user.
- ORDER BY (in OVER)
- Defines which row counts as previous or next. Required.
Visual diagram
Theory & example queries
How LAG and LEAD work
LAG(expr, offset, default) OVER (PARTITION BY … ORDER BY …) returns expr from the row offset positions earlier in the same partition. LEAD is the same in the other direction. Offset defaults to 1, and when the row doesn't exist (the first row for LAG, the last for LEAD) you get the default, or NULL.
PARTITION BY restarts the sequence for each group, so LAG(login_at) OVER (PARTITION BY user_id ORDER BY login_at) never compares one user's login with another user's. Without PARTITION BY, the whole result is one sequence.
SELECT user_id, login_at, login_at - LAG(login_at) OVER ( PARTITION BY user_id ORDER BY login_at ) AS gapFROM logins;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative login gaps4 sample rows
| user_id | login_at | gap |
|---|---|---|
| 7 | 2026-11-01T09:00:00+00:00 | NULL |
| 7 | 2026-11-02T10:30:00+00:00 | 1 day 01:30:00 |
| 7 | 2026-11-05T08:15:00+00:00 | 2 days 21:45:00 |
| 12 | 2026-11-03T18:00:00+00:00 | NULL |
Note: Illustrative PostgreSQL interval rendering. The first row in each user partition has NULL because no previous login exists.
Key takeaway: ORDER BY defines "previous"; PARTITION BY keeps groups separate.
Common patterns and pitfalls
Detecting changes: compare a column with its LAG and keep the rows where they differ, for example the moments a subscription's plan changed. Because window results can't be filtered in the same WHERE, put the LAG in a CTE and filter outside.
LAG works on rows, not on time. If a day has no row, LAG still returns the previous existing row, so a "day-over-day" change could really be over three days. Fill missing dates first (join to a calendar or generate_series) when gaps matter.
WITH x AS ( SELECT sub_id, changed_at, plan, LAG(plan) OVER ( PARTITION BY sub_id ORDER BY changed_at ) AS prev_plan FROM plan_history )SELECT *FROM xWHERE plan IS DISTINCT FROM prev_plan AND prev_plan IS NOT NULL;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative plan changes3 sample rows
| sub_id | changed_at | plan | prev_plan |
|---|---|---|---|
| 101 | 2026-09-12 | pro | free |
| 101 | 2026-11-03 | team | pro |
| 206 | 2026-10-18 | free | pro |
Note: Assumes these plan-history transitions are distinct and ordered by changed_at; each subscription's initial row is excluded because prev_plan is NULL.
Key takeaway: Filter LAG results in an outer query, and fill date gaps when "previous day" matters.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Decide what "previous" means
Choose the sort column (date, timestamp, version) and, if needed, a tiebreaker so rows with equal timestamps have a stable order.
ORDER BY login_at, idWhen to use it & trade-offs
What it is
LAG() returns a value from an earlier row and LEAD() from a later row, within the same window and sort order. LAG(revenue) OVER (ORDER BY month) gives last month's revenue on this month's row, so you can compute changes without a self join.
Why it matters: Day-over-day change, time since the previous login, detecting when a status changed: these "compare with the previous row" questions are everywhere in analytics and are a staple of SQL interviews. LAG and LEAD answer them in one pass.
When to reach for it
- Day-over-day, week-over-week and month-over-month changes
- Time between consecutive events (logins, orders)
- Detecting when a value changed
When to avoid or be careful
- Forgetting PARTITION BY and comparing one user's row with another user's
- Treating LAG as "previous calendar day" when days can be missing
- Filtering on LAG in the same SELECT's WHERE
LAG/LEAD vs self join vs correlated subquery
Strengths: One pass over the data, simple to read.
Watch out: Only neighbours in the sort order; date gaps aren't filled for you.
Strengths: Works everywhere.
Watch out: More code, and easy to get the join condition wrong.
Strengths: Flexible conditions.
Watch out: Usually much slower on large tables.
Interview signals & numbers to know
When this topic comes up
- “Compared with the previous day / month”
- “Time between orders”
- “When did the status change?”
- Consecutive rows
- Growth rate
Benchmarks & rules of thumb
- 1
- default offset
- NULL
- LAG on the first row unless you pass a default
- 3rd argument
- the default value
Common mistakes & follow-ups
Common interview mistakes
- Omitting PARTITION BY, so the first row of each user picks up the previous user's value.
- Computing growth as revenue / LAG(revenue) without handling NULL or zero in the previous value.
- Assuming the previous row is the previous day when the data has gaps.
Likely interviewer follow-ups
- How would you compute month-over-month growth as a percentage?
- How would you find users who logged in on two consecutive days?
- What does LAG return for the first row, and how can you change that?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Offset Functions: LAG() & LEAD() (Accessing Previous & Next Rows) with hands-on SQL practice and interview Q&A.