Learn how to use SQL's LEAD and LAG window functions to compare adjacent rows within a partition, calculate deltas, detect state transitions, and handle edge cases at partition boundaries — with production-ready examples throughout.

Imagine you're a data analyst at a subscription business. Your product team asks you a deceptively simple question: "Which customers upgraded their plan last month?" Simple to ask, surprisingly tricky to answer — because the answer lives not in a single row, but in the relationship between consecutive rows. You need to look at what a customer's plan was before, compare it to what it is now, and flag the ones that changed.
This is exactly the class of problem that LEAD and LAG were built to solve. These window functions let you reach forward and backward across rows within a defined partition, pulling in adjacent values so you can compute differences, detect state transitions, and reason about sequences — all without a single self-join. By the time you finish this lesson, you'll be writing the kind of queries that make your colleagues say "wait, how does that work?"
By the end of this lesson, you'll be able to:
What you'll learn:
LEAD and LAG, including their offset and default value parametersLEAD/LAG with CTEs and filtering to build production-ready analytical queriesYou should be comfortable with the core window function syntax — OVER(), PARTITION BY, and ORDER BY inside a window clause. If you need a refresher, the lesson on Window Functions: RANK, ROW_NUMBER, and LAG covers the fundamentals. You should also understand CASE WHEN expressions and basic NULL handling. Familiarity with Common Table Expressions (CTEs) will help you follow the more complex examples later in the article.
Before we write anything useful, let's establish exactly what these functions accept, because the full signature is more powerful than most people realize.
LAG(expression [, offset [, default]]) OVER (
[PARTITION BY partition_expression]
ORDER BY sort_expression
)
LEAD(expression [, offset [, default]]) OVER (
[PARTITION BY partition_expression]
ORDER BY sort_expression
)
LAG) or forward (LEAD) to look. Defaults to 1 if omitted.NULL.The ORDER BY inside the OVER() clause is not optional here — it defines the sequence in which rows are compared. PARTITION BY is optional, but in practice you almost always want it, because without it you're comparing rows across the entire result set regardless of which customer, product, or sensor they belong to.
Let's ground this with a concrete dataset. Suppose you have a monthly_revenue table that tracks revenue per customer per month:
CREATE TABLE monthly_revenue (
customer_id INT,
revenue_month DATE,
revenue NUMERIC(12, 2)
);
INSERT INTO monthly_revenue VALUES
(101, '2024-01-01', 4200.00),
(101, '2024-02-01', 5100.00),
(101, '2024-03-01', 4800.00),
(101, '2024-04-01', 6200.00),
(102, '2024-01-01', 1500.00),
(102, '2024-02-01', 1500.00),
(102, '2024-03-01', 1800.00),
(102, '2024-04-01', 1200.00);
A basic LAG query to retrieve the previous month's revenue looks like this:
SELECT
customer_id,
revenue_month,
revenue,
LAG(revenue) OVER (
PARTITION BY customer_id
ORDER BY revenue_month
) AS prev_month_revenue
FROM monthly_revenue
ORDER BY customer_id, revenue_month;
| customer_id | revenue_month | revenue | prev_month_revenue |
|---|---|---|---|
| 101 | 2024-01-01 | 4200.00 | NULL |
| 101 | 2024-02-01 | 5100.00 | 4200.00 |
| 101 | 2024-03-01 | 4800.00 | 5100.00 |
| 101 | 2024-04-01 | 6200.00 | 4800.00 |
| 102 | 2024-01-01 | 1500.00 | NULL |
| 102 | 2024-02-01 | 1500.00 | 1500.00 |
| 102 | 2024-03-01 | 1800.00 | 1500.00 |
| 102 | 2024-04-01 | 1200.00 | 1800.00 |
Notice the NULL on the first row of each customer's partition. That's the boundary condition in action — January has no prior month, so LAG has nothing to reach back to. We'll handle this properly in a moment.
Key insight
PARTITION BY customer_id is what prevents LAG from accidentally pulling the last row of customer 101 as the "previous" row for customer 102's first month. The partition resets the window for each customer independently.
Now that you can retrieve the previous row's value, computing a delta is straightforward arithmetic. Let's extend the query to calculate both the absolute change and the percentage change:
SELECT
customer_id,
revenue_month,
revenue,
LAG(revenue) OVER (
PARTITION BY customer_id
ORDER BY revenue_month
) AS prev_month_revenue,
revenue - LAG(revenue) OVER (
PARTITION BY customer_id
ORDER BY revenue_month
) AS revenue_delta,
ROUND(
100.0 * (revenue - LAG(revenue) OVER (
PARTITION BY customer_id
ORDER BY revenue_month
)) / NULLIF(LAG(revenue) OVER (
PARTITION BY customer_id
ORDER BY revenue_month
), 0),
2
) AS pct_change
FROM monthly_revenue
ORDER BY customer_id, revenue_month;
This works, but notice we're calling LAG() three times with identical arguments — that's repetitive and expensive. The database may or may not deduplicate those calls depending on the optimizer. The cleaner approach wraps the LAG calculation in a CTE so it's computed once:
WITH revenue_with_lag AS (
SELECT
customer_id,
revenue_month,
revenue,
LAG(revenue) OVER (
PARTITION BY customer_id
ORDER BY revenue_month
) AS prev_month_revenue
FROM monthly_revenue
)
SELECT
customer_id,
revenue_month,
revenue,
prev_month_revenue,
revenue - prev_month_revenue AS revenue_delta,
ROUND(
100.0 * (revenue - prev_month_revenue) / NULLIF(prev_month_revenue, 0),
2
) AS pct_change
FROM revenue_with_lag
ORDER BY customer_id, revenue_month;
| customer_id | revenue_month | revenue | prev_month_revenue | revenue_delta | pct_change |
|---|---|---|---|---|---|
| 101 | 2024-01-01 | 4200.00 | NULL | NULL | NULL |
| 101 | 2024-02-01 | 5100.00 | 4200.00 | 900.00 | 21.43 |
| 101 | 2024-03-01 | 4800.00 | 5100.00 | -300.00 | -5.88 |
| 101 | 2024-04-01 | 6200.00 | 4800.00 | 1400.00 | 29.17 |
Tip
Wrapping LAG() calls in a CTE is a best practice for readability and maintainability. It also gives the query optimizer a single materialization point. For more on structuring complex queries this way, see the article on Common Table Expressions (CTEs) for Cleaner SQL.
The NULLIF(prev_month_revenue, 0) protects against division-by-zero when a customer had zero revenue in the prior month. If you need to understand NULL handling more deeply, the article on SQL NULL Handling: COALESCE, NULLIF, and IS NULL covers these edge cases thoroughly.
The NULL on the first row of each partition is unavoidable in the base case — there simply is no prior row. But you have several strategies for handling it, depending on what your analysis needs.
The third argument to LAG lets you specify a fallback value when the function hits a boundary:
SELECT
customer_id,
revenue_month,
revenue,
LAG(revenue, 1, 0) OVER (
PARTITION BY customer_id
ORDER BY revenue_month
) AS prev_month_revenue
FROM monthly_revenue;
Here, the first row of each customer's partition will show 0 instead of NULL. Whether this is appropriate depends on your business logic. For revenue deltas, using 0 as the default means you'd report January's full revenue as a "gain from zero" — which may or may not be what you want.
If you're building a report that only makes sense for rows where a comparison exists, exclude the NULLs explicitly:
WITH revenue_with_lag AS (
SELECT
customer_id,
revenue_month,
revenue,
LAG(revenue) OVER (
PARTITION BY customer_id
ORDER BY revenue_month
) AS prev_month_revenue
FROM monthly_revenue
)
SELECT *
FROM revenue_with_lag
WHERE prev_month_revenue IS NOT NULL
ORDER BY customer_id, revenue_month;
Sometimes you want a smarter default — like the customer's first-ever recorded revenue, or a company-wide baseline. COALESCE lets you express this cleanly:
WITH revenue_with_lag AS (
SELECT
customer_id,
revenue_month,
revenue,
LAG(revenue) OVER (
PARTITION BY customer_id
ORDER BY revenue_month
) AS prev_month_revenue,
FIRST_VALUE(revenue) OVER (
PARTITION BY customer_id
ORDER BY revenue_month
) AS first_ever_revenue
FROM monthly_revenue
)
SELECT
customer_id,
revenue_month,
revenue,
COALESCE(prev_month_revenue, first_ever_revenue) AS comparison_revenue,
revenue - COALESCE(prev_month_revenue, first_ever_revenue) AS delta
FROM revenue_with_lag
ORDER BY customer_id, revenue_month;
For the first row of each partition, prev_month_revenue is NULL, so COALESCE falls back to first_ever_revenue — which is the same value as revenue on row one, giving a delta of zero. This cleanly communicates "no change to report" without introducing misleading numbers.
Warning
Using 0 as a default for LAG can silently distort percentage change calculations. A revenue of $5000 with a previous of $0 produces an infinite percentage gain. Always think carefully about what boundary rows should mean in your specific analytical context.
Calculating numeric deltas is useful, but LAG really shines when you're detecting categorical changes — a customer moving from one subscription tier to another, an order status changing from pending to shipped, a sensor reading crossing a threshold.
Here's the subscription tier scenario from the introduction. Suppose you have an account_history table:
CREATE TABLE account_history (
customer_id INT,
effective_dt DATE,
plan_name VARCHAR(50),
plan_tier INT -- 1=Basic, 2=Pro, 3=Enterprise
);
INSERT INTO account_history VALUES
(201, '2024-01-15', 'Basic', 1),
(201, '2024-03-01', 'Pro', 2),
(201, '2024-06-15', 'Enterprise', 3),
(202, '2024-02-01', 'Pro', 2),
(202, '2024-04-01', 'Basic', 1),
(203, '2024-01-01', 'Basic', 1),
(203, '2024-01-01', 'Basic', 1); -- duplicate, edge case
To identify upgrades and downgrades:
WITH plan_transitions AS (
SELECT
customer_id,
effective_dt,
plan_name,
plan_tier,
LAG(plan_name) OVER (
PARTITION BY customer_id
ORDER BY effective_dt, plan_tier
) AS prev_plan_name,
LAG(plan_tier) OVER (
PARTITION BY customer_id
ORDER BY effective_dt, plan_tier
) AS prev_plan_tier
FROM account_history
)
SELECT
customer_id,
effective_dt,
prev_plan_name,
plan_name AS new_plan_name,
CASE
WHEN prev_plan_tier IS NULL THEN 'Initial signup'
WHEN plan_tier > prev_plan_tier THEN 'Upgrade'
WHEN plan_tier < prev_plan_tier THEN 'Downgrade'
ELSE 'No change'
END AS transition_type
FROM plan_transitions
ORDER BY customer_id, effective_dt;
| customer_id | effective_dt | prev_plan_name | new_plan_name | transition_type |
|---|---|---|---|---|
| 201 | 2024-01-15 | NULL | Basic | Initial signup |
| 201 | 2024-03-01 | Basic | Pro | Upgrade |
| 201 | 2024-06-15 | Pro | Enterprise | Upgrade |
| 202 | 2024-02-01 | NULL | Pro | Initial signup |
| 202 | 2024-04-01 | Pro | Basic | Downgrade |
| 203 | 2024-01-01 | NULL | Basic | Initial signup |
| 203 | 2024-01-01 | Basic | Basic | No change |
The ORDER BY effective_dt, plan_tier in the window clause is a deliberate choice. When two events share the same timestamp (like customer 203's duplicate rows), adding a tiebreaker — plan_tier here, or a surrogate key if you have one — prevents non-deterministic ordering, which would make your results unreliable.
Warning
If your ORDER BY inside the window clause isn't deterministic (i.e., rows can legitimately tie on all sort keys), LAG and LEAD will return unpredictable results. Always ensure the ordering uniquely identifies row sequence within a partition.
LEAD is LAG's mirror image — instead of looking backward, it peeks at the next row. This is useful for calculating durations, finding when a state ends, or generating "time until next event" metrics.
Consider the same account_history table. How long did each customer stay on each plan? To compute that, you need to know when the next plan started:
WITH plan_durations AS (
SELECT
customer_id,
effective_dt AS plan_start,
plan_name,
LEAD(effective_dt) OVER (
PARTITION BY customer_id
ORDER BY effective_dt
) AS next_plan_start
FROM account_history
)
SELECT
customer_id,
plan_start,
plan_name,
COALESCE(next_plan_start, CURRENT_DATE) AS plan_end,
COALESCE(next_plan_start, CURRENT_DATE) - plan_start AS days_on_plan
FROM plan_durations
ORDER BY customer_id, plan_start;
The boundary condition here is at the last row of each partition — the customer's current plan has no known end date. Using COALESCE(next_plan_start, CURRENT_DATE) treats the current date as the plan end, giving you a "so far" duration. If your business rules differ (e.g., use a fixed reporting cutoff date), replace CURRENT_DATE with that date.
This kind of forward-looking query pairs beautifully with time-series analyses. If you're building retention or cohort models, the article on SQL for Data Analysis: Cohort Analysis, Funnels, and Retention shows how LEAD-derived durations feed directly into funnel step timing.
The offset parameter lets you reach further than just one row. This is useful for period-over-period comparisons at different granularities — comparing this month to the same month last year, for example.
Suppose you have weekly sales data and want to compare each week to the same week four weeks prior:
CREATE TABLE weekly_sales (
region VARCHAR(50),
week_start DATE,
units_sold INT
);
WITH sales_with_prior AS (
SELECT
region,
week_start,
units_sold,
LAG(units_sold, 4) OVER (
PARTITION BY region
ORDER BY week_start
) AS units_4wks_ago,
LAG(units_sold, 52) OVER (
PARTITION BY region
ORDER BY week_start
) AS units_52wks_ago
FROM weekly_sales
)
SELECT
region,
week_start,
units_sold,
units_sold - units_4wks_ago AS delta_vs_4w,
units_sold - units_52wks_ago AS delta_vs_52w,
ROUND(
100.0 * (units_sold - units_52wks_ago)
/ NULLIF(units_52wks_ago, 0),
1
) AS yoy_pct_change
FROM sales_with_prior
ORDER BY region, week_start;
The 52-row offset here assumes weekly data with no gaps. If your data has missing weeks, LAG(units_sold, 52) won't reach exactly one year back — it'll reach 52 present rows back, which might land somewhere unexpected. For gap-sensitive time comparisons, the approach in Temporal Data Mastery: Writing Queries for Time-Series, Date Ranges, and Slowly Changing Dimensions is worth reading — it covers how to join on explicit date ranges rather than relying on positional offsets.
Key insight
LAG(col, N) counts rows, not time intervals. If your data has gaps — missing months, sparse event logs — positional offsets will silently compare against the wrong period. Always validate that your data is dense and regular before relying on numeric offsets for time-based comparisons.
One of the most powerful patterns is using LEAD and LAG simultaneously to identify the start and end of contiguous "islands" — runs of rows that share a common state.
Consider IoT sensor data where a machine is either running or down:
CREATE TABLE machine_status (
machine_id VARCHAR(20),
reading_ts TIMESTAMP,
status VARCHAR(10) -- 'running' or 'down'
);
We want to identify every downtime incident: when it started, when it ended, and how long it lasted. The approach:
LAG to flag rows where the status changed from something different (start of a new state)LEAD to find where the state changes next (end of the current state)WITH status_with_neighbors AS (
SELECT
machine_id,
reading_ts,
status,
LAG(status) OVER (
PARTITION BY machine_id
ORDER BY reading_ts
) AS prev_status,
LEAD(reading_ts) OVER (
PARTITION BY machine_id
ORDER BY reading_ts
) AS next_reading_ts,
LEAD(status) OVER (
PARTITION BY machine_id
ORDER BY reading_ts
) AS next_status
FROM machine_status
),
state_changes AS (
SELECT
machine_id,
reading_ts,
status,
-- A row is a "boundary start" if its status differs from the previous row
CASE
WHEN prev_status IS NULL OR status != prev_status THEN 1
ELSE 0
END AS is_state_start
FROM status_with_neighbors
),
island_groups AS (
SELECT
machine_id,
reading_ts,
status,
-- Running sum of state starts gives each island a unique group number
SUM(is_state_start) OVER (
PARTITION BY machine_id
ORDER BY reading_ts
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS state_group
FROM state_changes
)
SELECT
machine_id,
status,
MIN(reading_ts) AS state_started_at,
MAX(reading_ts) AS last_seen_at,
EXTRACT(EPOCH FROM (MAX(reading_ts) - MIN(reading_ts))) / 60 AS duration_minutes
FROM island_groups
WHERE status = 'down'
GROUP BY machine_id, status, state_group
ORDER BY machine_id, state_started_at;
This three-CTE pattern — neighbors → state_changes → island_groups — is a classic SQL technique for session analysis and gap detection. The key insight is that the running SUM of is_state_start acts as a group identifier: every time a state transition happens, the counter increments, giving all rows within the same contiguous run the same group number.
Tip
This "islands and gaps" pattern comes up constantly in event log analysis — customer sessions, server uptime tracking, subscription status history, and sequential test runs. Once you recognize the structure, the three-CTE scaffold becomes second nature. See how this connects to Advanced CTEs: Recursive Queries and Hierarchical Data for related sequential data patterns.
LEAD and LAG are computed during the window function pass, which means the database reads the relevant partition once and applies the offset lookup in memory. This is almost always more efficient than a self-join alternative.
Compare the LAG-based approach to the equivalent self-join:
-- Self-join approach (avoid this)
SELECT
a.customer_id,
a.revenue_month,
a.revenue,
b.revenue AS prev_month_revenue
FROM monthly_revenue a
LEFT JOIN monthly_revenue b
ON a.customer_id = b.customer_id
AND b.revenue_month = a.revenue_month - INTERVAL '1 month';
The self-join requires a second scan of the table and a potentially expensive join operation. With a date-based join condition like this, it also breaks silently if there are gaps in monthly data. The LAG version is both cleaner and more efficient.
That said, window functions do have overhead on very large tables. The database must sort rows within each partition — O(n log n) per partition — before applying the offset. For tables in the tens of millions of rows with many partitions, this can be significant.
An index on (partition_key, order_key) — in this case (customer_id, revenue_month) — dramatically reduces the sort cost because the data arrives in the right order. For more on how indexes interact with window function performance, the article on Database Performance Tuning: Advanced Indexing Strategies and Query Rewriting for Production Systems goes deep on this.
Note
If you're writing LEAD and LAG over the same partition and order, modern databases (PostgreSQL, SQL Server, BigQuery, Snowflake) are smart enough to perform a single sort pass for all window functions that share the same OVER() specification. Write all such functions in the same query layer — don't split them across multiple CTEs if they share the same window — to give the optimizer the best chance of combining them.
Let's build something realistic end to end. You're working with an e-commerce platform's order data:
CREATE TABLE customer_orders (
order_id INT,
customer_id INT,
order_date DATE,
order_total NUMERIC(10, 2),
order_status VARCHAR(20)
);
INSERT INTO customer_orders VALUES
(1001, 501, '2024-01-05', 89.99, 'completed'),
(1002, 501, '2024-02-12', 145.00, 'completed'),
(1003, 501, '2024-03-18', 220.50, 'completed'),
(1004, 501, '2024-05-02', 310.00, 'completed'),
(1005, 502, '2024-01-20', 55.00, 'completed'),
(1006, 502, '2024-02-28', 55.00, 'completed'),
(1007, 502, '2024-04-10', 180.00, 'completed'),
(1008, 503, '2024-03-01', 999.00, 'completed'),
(1009, 503, '2024-03-15', 450.00, 'returned'),
(1010, 503, '2024-04-20', 220.00, 'completed');
Your task: Write a query that produces a report showing, for each order:
'First order', 'Spending more', 'Spending less', or 'Same amount'Try this yourself before reading the solution.
Solution:
WITH order_history AS (
SELECT
order_id,
customer_id,
order_date,
order_total,
order_status,
LAG(order_total) OVER (
PARTITION BY customer_id
ORDER BY order_date, order_id
) AS prev_order_total,
LAG(order_date) OVER (
PARTITION BY customer_id
ORDER BY order_date, order_id
) AS prev_order_date
FROM customer_orders
)
SELECT
order_id,
customer_id,
order_date,
order_total,
order_status,
prev_order_date,
prev_order_total,
order_total - prev_order_total AS spend_delta,
order_date - prev_order_date AS days_since_prev_order,
CASE
WHEN prev_order_total IS NULL THEN 'First order'
WHEN order_total > prev_order_total THEN 'Spending more'
WHEN order_total < prev_order_total THEN 'Spending less'
ELSE 'Same amount'
END AS spend_trend
FROM order_history
ORDER BY customer_id, order_date;
Notice the ORDER BY order_date, order_id in the window clause. When two orders share the same date (which could happen), the order_id acts as a deterministic tiebreaker. This is a habit worth forming — always include a unique key as the final sort criterion in your window order.
-- WRONG: No PARTITION BY
SELECT
customer_id,
revenue_month,
LAG(revenue) OVER (ORDER BY revenue_month) AS prev_revenue
FROM monthly_revenue;
This pulls the last row of whatever customer sorts earlier as the "previous" row for the first row of the next customer. The result looks plausible, which makes it dangerous. Always double-check your PARTITION BY clause.
If your ORDER BY has ties, the database can return different rows as "previous" on different runs. The fix is always to add a unique key — typically a surrogate ID or timestamp with microsecond precision — as the final tiebreaker.
This one is subtle. If you do this:
-- WRONG: filtering before the window function sees all rows
WITH filtered AS (
SELECT * FROM customer_orders WHERE order_status = 'completed'
)
SELECT
customer_id,
order_date,
LAG(order_total) OVER (PARTITION BY customer_id ORDER BY order_date)
FROM filtered;
...and customer 503's returned order (order 1009) is excluded, then order 1010's "previous" order becomes order 1008 — which may or may not be what you want. If you're filtering before the LAG computation, make sure you've explicitly decided that filtered rows shouldn't count as "previous."
As mentioned earlier, LAG(col, 1) looks at the immediately preceding row in the partition, not the row from exactly one time unit prior. If your data has gaps, the previous row might be from two months ago or two years ago. Always check whether positional adjacency is what your business logic actually requires.
NULL - 300 = NULL. If prev_month_revenue is NULL (boundary row), then revenue - prev_month_revenue will also be NULL. This is usually correct behavior, but it can surprise you in aggregations. If you're doing SUM(revenue_delta), the first row of each partition silently contributes nothing to the total — which may undercount your overall revenue change.
LEAD and LAG are indispensable tools for any data professional working with sequential, time-ordered, or event-based data. Here's what we covered:
expression, offset, and default parameters — and why the default matters at boundariesLAG in a CTE to compute deltas cleanly without redundant function callsCASE WHEN on LAG values to classify transitions as upgrades, downgrades, or no-changesLEAD to calculate durations and "time until next event"LEAD, LAG, and running SUM to find contiguous runs of a state(partition_key, order_key) helpWhere to go next:
The pattern you've learned here — look at neighbors, compute a relationship, classify or quantify the change — underpins a surprising fraction of real-world analytical SQL. Once it's in your toolkit, you'll start recognizing the shape of these problems everywhere.
Advanced SQL Queries