Learn SQL
-- windows.lag_lead

LAG & LEAD in SQL

Reach to the previous or next row in one ORDER

--concept

LAG(column) fetches a value from the previous row of the window; LEAD(column) from the next. Comparing each row with its neighbour — month-over-month change, gap since last order, time between events — becomes a self-join-free one-liner. Both take an optional offset (LAG(x, 2) = two rows back) and a default for the boundary rows.

--how it works
1

Fix the row order

OVER (ORDER BY id) defines the sequence — LAG reaches one row “back” in it, LEAD one row “forward”.

2

Fetch the neighbour value

LAG(salary) OVER (…) returns the previous row’s salary as an ordinary column on the current row — no self-join, no correlated subquery.

3

Compute the difference inline

salary − LAG(salary) OVER (…) AS delta — month-over-month change, gap between events, step size.

4

Handle the edges deliberately

The first row has no predecessor: LAG returns NULL, or your default — LAG(salary, 1, 0). LEAD mirrors at the far end.

5

Partition to restart per group

LAG(salary) OVER (PARTITION BY department ORDER BY id) — each employee compares to their department-mate, never across departments.

--visualization
Alice85kBob52kCynthia91kDavid47kElena58kFarid73kprev_salary · deltasalary − LAG(salary) OVER (ORDER BY id) — month-over-month, gap analysis, sessionising
positive delta negative / NULL edge
Stage 1 / 7
OVER (ORDER BY id) lines the rows up — LAG reads the previous row, LEAD the next. One sort, then pure neighbour reads.
--example
query.sql
1SELECT name, salary,
2 LAG(salary) OVER (ORDER BY id) AS prev_salary,
3 salary - LAG(salary) OVER (ORDER BY id) AS delta
4FROM employees ORDER BY id;
Result
namesalaryprev_salarydelta
Alice85000nullnull
Bob5200085000-33000
Cynthia910005200039000
David4700091000-44000
Elena580004700011000
Farid730005800015000

Each row carries its neighbour’s salary alongside its own: Bob’s delta is 52,000 − 85,000 = −33,000. Alice, first in the order, has no previous row — LAG yields NULL and so does the difference. The whole comparison is one pass over sorted data.

--variants

Difference from the previous row

One pass, no join — the LAG signature move.

query.sql
1SELECT name, salary,
2 LAG(salary) OVER (ORDER BY id) AS prev_salary,
3 salary - LAG(salary) OVER (ORDER BY id) AS delta
4FROM employees ORDER BY id;
Result
namesalaryprev_salarydelta
Alice85000nullnull
Bob5200085000-33000
Cynthia910005200039000
David4700091000-44000
Elena580004700011000
Farid730005800015000
1Bob’s row carries Alice’s salary next to his own: 52,000 − 85,000 = −33,000.
2Alice is first in id order — no predecessor, so prev_salary and delta are NULL.
3The pre-window way to do this was a self-join on id = id − 1 — slower, uglier, edge-case-prone.

Previous row within the department

PARTITION BY keeps comparisons inside the group.

query.sql
1SELECT name, department, salary,
2 LAG(salary) OVER (PARTITION BY department ORDER BY salary) AS lower_paid
3FROM employees WHERE department = 'Engineering' ORDER BY salary;
Result
namedepartmentsalarylower_paid
FaridEngineering73000null
AliceEngineering8500073000
CynthiaEngineering9100085000
1Engineering alone in the partition: Farid is first → NULL; Alice sees 73,000; Cynthia sees 85,000.
2Without PARTITION BY, Alice’s “previous” could have been a Sales employee.
3The gap between neighbours is one expression away: salary − LAG(salary) …

LEAD with a default

The last row can carry a sentinel instead of NULL.

query.sql
1SELECT name, salary,
2 LEAD(salary, 1, 0) OVER (ORDER BY id) AS next_salary
3FROM employees WHERE department = 'Sales' ORDER BY id;
Result
namesalarynext_salary
Bob5200058000
Elena580000
1Bob looks ahead to Elena’s 58,000.
2Elena is the last row; the three-argument LEAD supplies 0 instead of NULL.
3COALESCE(LEAD(…), 0) is equivalent and sometimes clearer.

Time between events

Timestamps + LAG = inter-arrival analysis.

query.sql
1SELECT order_id, placed_at,
2 placed_at - LAG(placed_at) OVER (PARTITION BY customer_id ORDER BY placed_at) AS since_prev
3FROM orders ORDER BY customer_id, placed_at;
Result
order_idplaced_atsince_prev
#1012026-08-28 09:14null
#1022026-08-30 18:402 days 09:26
#1032026-09-02 11:052 days 16:25
1Each customer’s orders are chained in time; since_prev measures the gap to their previous order.
2The first order per customer has no predecessor — NULL, as it should be.
3Averages of this column become “typical days between purchases” — a churn signal hiding in one window call.
--key facts
NULL at the edgethe first row has no LAG, the last has no LEAD — COALESCE a default if needed
OffsetsLAG(x, 3) reaches three rows back — same cost, still one sort
Gaps and islandsLAG + differences is the standard toolkit for sessionising event logs
--use cases
Month-over-month / day-over-day deltas in reporting
Sessionisation: flag a new session when the gap since the previous event exceeds a threshold
Funnel step analysis: time from signup to first purchase
Gaps-and-islands: consecutive-streak detection with LAG + running sums
--under the hood
LAG/LEAD read from the already-sorted window stream — after the (partition, order) sort, each neighbour lookup is O(1).
Row-store engines materialise the partition buffer; huge PARTITION BY groups are the memory watch-point.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.