Sub topic 7
Looking at neighbouring rows with LAG and LEAD
This chapter assumes you can read an OVER (PARTITION BY ... ORDER BY ...) clause and know what a CTE is. LAG and LEAD let a row read a value from another row in the same partition, without a self-join.
What LAG and LEAD do
LAG returns a value from an earlier row. LEAD returns a value from a later row. "Earlier" and "later" are defined only by the window's ORDER BY, not by how the rows are stored.
The general form is:
LAG(expression [, offset [, default]]) OVER ([PARTITION BY ...] ORDER BY ...)
LEAD(expression [, offset [, default]]) OVER ([PARTITION BY ...] ORDER BY ...)expressionis the value to fetch, usually a column.offsetis how many rows to move. It defaults to 1.defaultis returned when the target row does not exist. It defaults toNULL.
Month-over-month change
Create a small table to follow along. The statements work in PostgreSQL, MySQL 8+, SQLite 3.25+ and SQL Server 2022 (SQL Server needs DATE values in 'YYYY-MM-DD' form, which these are).
CREATE TABLE monthly_revenue (
sale_month DATE PRIMARY KEY,
revenue INTEGER NOT NULL
);
INSERT INTO monthly_revenue (sale_month, revenue) VALUES
('2025-01-01', 12000),
('2025-02-01', 13500),
('2025-03-01', 12900),
('2025-04-01', 15600);Now compare each month with the month before it:
SELECT
sale_month,
revenue,
LAG(revenue) OVER (ORDER BY sale_month) AS prev_revenue,
revenue - LAG(revenue) OVER (ORDER BY sale_month) AS change_from_prev
FROM monthly_revenue;| sale_month | revenue | prev_revenue | change_from_prev |
|---|---|---|---|
| 2025-01-01 | 12000 | NULL | NULL |
| 2025-02-01 | 13500 | 12000 | 1500 |
| 2025-03-01 | 12900 | 13500 | -600 |
| 2025-04-01 | 15600 | 12900 | 2700 |
January has no earlier row, so LAG returns NULL. Any arithmetic with NULL also gives NULL, so the first change is NULL too.
The window is written twice. If this bothers you, move the lag into a CTE or use a named window (a later chapter covers the WINDOW clause). Both calls use the same ordering, so the database can compute them in one sort.
Percent change and division by zero
A percentage change divides by the previous value. If that value is 0, the division fails in PostgreSQL and SQL Server. NULLIF(x, 0) turns a zero into NULL, which makes the result NULL instead of an error.
SELECT
sale_month,
revenue,
ROUND(
(revenue - LAG(revenue) OVER (ORDER BY sale_month)) * 100.0
/ NULLIF(LAG(revenue) OVER (ORDER BY sale_month), 0),
1
) AS pct_change
FROM monthly_revenue;The result is NULL, 12.5, -4.4 and 20.9 for the four months. Multiplying by 100.0 rather than 100 forces decimal division. With integer columns, 100 can make some databases truncate the result.
Offsets and defaults
The second argument moves further back. If you have one row per month and want the same month a year earlier, use an offset of 12:
SELECT
sale_month,
revenue,
LAG(revenue, 12) OVER (ORDER BY sale_month) AS same_month_last_year
FROM monthly_revenue;The third argument replaces NULL for rows that fall off the edge:
SELECT
sale_month,
revenue,
LAG(revenue, 1, 0) OVER (ORDER BY sale_month) AS prev_revenue
FROM monthly_revenue;Here January shows a previous revenue of 0. Think before using a default. A 0 makes the January "change" equal to the whole revenue, which is a claim about the data that the data does not support. NULL is usually the more honest answer for "no earlier row".
An offset of 0 returns the current row. Negative offsets are rejected by most databases. To look in the other direction, use the other function.
LEAD: looking forward
LEAD is LAG with the direction reversed. A common use is the gap until the next event. This example uses a logins table where day_no is an integer day number:
CREATE TABLE logins (day_no INTEGER PRIMARY KEY);
INSERT INTO logins (day_no) VALUES (1), (2), (4), (7), (8);
SELECT
day_no,
LEAD(day_no) OVER (ORDER BY day_no) AS next_day,
LEAD(day_no) OVER (ORDER BY day_no) - day_no AS days_until_next
FROM logins;| day_no | next_day | days_until_next |
|---|---|---|
| 1 | 2 | 1 |
| 2 | 4 | 2 |
| 4 | 7 | 3 |
| 7 | 8 | 1 |
| 8 | NULL | NULL |
The last row has no later row, so it gets NULL. Rows with days_until_next > 1 mark the places where a streak ends.
LAG and LEAD inside partitions
Without PARTITION BY, the whole result set is one window. If the table holds several products, the first month of product B would "see" the last month of product A. Partitioning restarts the sequence for each group:
SELECT
product,
sale_month,
revenue,
revenue - LAG(revenue) OVER (
PARTITION BY product
ORDER BY sale_month
) AS change_from_prev
FROM product_revenue;Each product's first row gets NULL, because the lookup never crosses a partition boundary. This is the most common bug in LAG queries: a missing PARTITION BY that produces plausible numbers at the group boundaries.
Filtering on a LAG result
You cannot write WHERE revenue < LAG(revenue) OVER (...), because WHERE is evaluated before window functions. Compute the lag in a CTE, then filter in the outer query:
WITH changes AS (
SELECT
sale_month,
revenue,
revenue - LAG(revenue) OVER (ORDER BY sale_month) AS change_from_prev
FROM monthly_revenue
)
SELECT sale_month, revenue, change_from_prev
FROM changes
WHERE change_from_prev < 0;This returns March only. January is excluded as well, because NULL < 0 is not true.
Gotchas
LAG counts rows, not calendar units
LAG(revenue, 1) returns the previous row that exists. If April is missing from the table, May's "previous month" is March, and the change spans two months without any warning. For data with possible gaps, either join to a calendar table first, or compare the dates as well. For example, return the change only when the previous date is exactly one month before.
Ties make the order ambiguous
If two rows have the same value in the window ORDER BY, the database may place them in either order, and the answer can change between runs. Add a unique tie-breaker, such as the primary key:
LAG(amount) OVER (ORDER BY sale_date, id)NULL in the data looks like NULL from the edge
If the previous row's value is itself NULL, LAG returns NULL, and you cannot tell it apart from a missing row. Some databases, including Oracle and SQL Server 2022, accept IGNORE NULLS to skip over NULL values. PostgreSQL and MySQL do not. Check your database's documentation before relying on it.
Frames do not apply
LAG and LEAD ignore the frame clause (ROWS BETWEEN ...). They always look at the whole partition in the window order, relative to the current row. Some databases reject a frame on these functions.
Dialect summary
| Behaviour | PostgreSQL | MySQL 8+ | SQL Server | SQLite 3.25+ |
|---|---|---|---|---|
| LAG and LEAD available | Yes | Yes | 2012 and later | Yes |
| `ORDER BY` required in `OVER` | Allowed to omit, but order is then undefined | Allowed to omit, but order is then undefined | Required | Allowed to omit, but order is then undefined |
| `IGNORE NULLS` | No | No | 2022 and later | No |
Exercise
Using the logins table above (days 1, 2, 4, 7, 8), write a query that returns only the days that start a new streak. A day starts a streak if it is the first day, or if the previous login day was more than 1 day earlier.
Show answer
WITH prev AS (
SELECT
dayno,
LAG(dayno) OVER (ORDER BY dayno) AS prevday
FROM logins
)
SELECT dayno
FROM prev
WHERE prevday IS NULL OR dayno - prevday > 1;
The result is days 1, 4 and 7. The IS NULL test keeps the first row, which has no earlier row. The window function must sit in a CTE because it cannot appear in WHERE.
Exercise
A table product_revenue(product, sale_month, revenue) holds monthly revenue for several products. Write a query that shows, for each row, the next month's revenue for the same product, and explain what the last row of each product shows.
Show answer
SELECT product, salemonth, revenue, LEAD(revenue) OVER (PARTITION BY product ORDER BY salemonth) AS nextmonthrevenue FROM productrevenue; The last month of each product has no later row inside its partition, so nextmonth_revenue is NULL. Without PARTITION BY, it would show the first month of the next product instead.