Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 85/ 160
05. Window Functions & Analytical SQL

Offset Functions: LAG() & LEAD() (Accessing Previous & Next Rows)

Look backward and forward within a partition for deltas and comparisons.

BeginnerLAG · LEAD · Offset3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Time between a user's loginsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  user_id,3  login_at,4  login_at - LAG(login_at) OVER (5    PARTITION BY6      user_id7    ORDER BY8      login_at9  ) AS gap10FROM11  logins;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative login gaps4 sample rows
Representative login gaps
user_idlogin_atgap
72026-11-01T09:00:00+00:00NULL
72026-11-02T10:30:00+00:001 day 01:30:00
72026-11-05T08:15:00+00:002 days 21:45:00
122026-11-03T18:00:00+00:00NULL

Note: Illustrative PostgreSQL interval rendering. The first row in each user partition has NULL because no previous login exists.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

When did each subscription change plan?Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  x AS (3    SELECT4      sub_id,5      changed_at,6      plan,7      LAG(plan) OVER (8        PARTITION BY9          sub_id10        ORDER BY11          changed_at12      ) AS prev_plan13    FROM14      plan_history15  )16SELECT17  *18FROM19  x20WHERE21  plan IS DISTINCT FROM prev_plan22  AND prev_plan IS NOT NULL;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/22
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative plan changes3 sample rows
Representative plan changes
sub_idchanged_atplanprev_plan
1012026-09-12profree
1012026-11-03teampro
2062026-10-18freepro

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Filter LAG results in an outer query, and fill date gaps when "previous day" matters.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1ORDER BY

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.

SQL at this step
1ORDER BY2  login_at,3  id
What to watch at this step
Required
yes
Tip: use ← → to move between steps

When 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

LAG / LEAD
Best for: Comparing each row with the previous or next row

Strengths: One pass over the data, simple to read.

Watch out: Only neighbours in the sort order; date gaps aren't filled for you.

Self join on row number or date
Best for: Databases without window functions

Strengths: Works everywhere.

Watch out: More code, and easy to get the join condition wrong.

Correlated subquery (MAX of earlier rows)
Best for: Fetching a previous value under a complex condition

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?
Interview tip: Say which column defines "previous" and which defines the group before writing anything. Most LAG bugs come from a missing PARTITION BY or the wrong ORDER BY.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Distribution & Bucketing Functions: NTILE(), PERCENT_RANK(), CUME_DIST()
Next topic
Value Functions: FIRST_VALUE(), LAST_VALUE(), NTH_VALUE()