Sub topic 11
Looking ahead with LEAD
LEAD is an analytic function that returns a column value from a row that follows the current row. It is the mirror image of LAG, and most of what you learned about LAG applies unchanged. This chapter assumes you know OVER, PARTITION BY, the window ORDER BY, and the LAG offset and default arguments.
Syntax and behavior
LEAD(expression [, offset [, default]]) OVER ([PARTITION BY ...] ORDER BY ...)expressionis the value to fetch from the following row. It can be a column or any expression.offsetis how many rows ahead to look. It defaults to 1 and must be a non-negative integer.defaultis returned when no row exists at that offset. It defaults toNULL.
The ORDER BY inside OVER is required. Without an order, "next" has no meaning, so Oracle rejects the query. PARTITION BY is optional. When you use it, LEAD never crosses a partition boundary. The last row of each partition gets the default.
A first example
Assume this table:
CREATE TABLE monthly_sales (
sales_month DATE,
amount NUMBER(10,2)
);
INSERT ALL
INTO monthly_sales VALUES (DATE '2026-01-01', 100)
INTO monthly_sales VALUES (DATE '2026-02-01', 120)
INTO monthly_sales VALUES (DATE '2026-03-01', 90)
INTO monthly_sales VALUES (DATE '2026-04-01', 150)
SELECT * FROM dual;This query shows the three common forms side by side:
SELECT sales_month,
amount,
LEAD(amount) OVER (ORDER BY sales_month) AS next_amount,
LEAD(amount, 1, 0) OVER (ORDER BY sales_month) AS next_or_zero,
LEAD(amount, 2) OVER (ORDER BY sales_month) AS two_ahead
FROM monthly_sales
ORDER BY sales_month;| SALES_MONTH | AMOUNT | NEXT_AMOUNT | NEXT_OR_ZERO | TWO_AHEAD |
|---|---|---|---|---|
| 2026-01-01 | 100 | 120 | 120 | 90 |
| 2026-02-01 | 120 | 90 | 90 | 150 |
| 2026-03-01 | 90 | 150 | 150 | NULL |
| 2026-04-01 | 150 | NULL | 0 | NULL |
The last row has no successor, so next_amount is NULL and next_or_zero is 0. With an offset of 2, the last two rows fall off the end.
LEAD and LAG are the same function reversed
LEAD(x) OVER (ORDER BY c) returns the same value as LAG(x) OVER (ORDER BY c DESC). The two rows are reached by walking the sorted partition in opposite directions. Choose the one that reads naturally. Use LEAD when the question is "what happens next?" and LAG when it is "what happened before?" Mixing both in one query is fine, because each function carries its own OVER clause.
Looking ahead within groups
Add PARTITION BY when each group has its own sequence. A common case is a price history, where each row is valid until the next row for the same product begins.
CREATE TABLE price_history (
product_id NUMBER,
valid_from DATE,
price NUMBER(8,2)
);
INSERT ALL
INTO price_history VALUES (1, DATE '2026-01-01', 10.00)
INTO price_history VALUES (1, DATE '2026-03-15', 11.50)
INTO price_history VALUES (1, DATE '2026-06-01', 12.00)
INTO price_history VALUES (2, DATE '2026-02-01', 40.00)
INTO price_history VALUES (2, DATE '2026-05-10', 38.00)
SELECT * FROM dual;
SELECT product_id,
price,
valid_from,
LEAD(valid_from - 1, 1, DATE '9999-12-31') OVER (
PARTITION BY product_id
ORDER BY valid_from
) AS valid_to
FROM price_history
ORDER BY product_id, valid_from;For product 1, the first row ends on 2026-03-14, the day before the next price starts. The last row of each product gets the default 9999-12-31, which means "still current". Because the expression valid_from - 1 is computed on the following row, you get the end date directly, with no self join.
The default argument matters here. A plain LEAD(valid_from) would leave NULL for open-ended rows, and you would need an extra NVL. Putting the sentinel date in the default keeps the logic in one place.
Measuring the distance to the next event
Date arithmetic with LEAD finds gaps. This query lists customers who waited more than 30 days between consecutive orders:
SELECT customer_id, order_date, next_order_date, gap_days
FROM (
SELECT customer_id,
order_date,
LEAD(order_date) OVER (
PARTITION BY customer_id
ORDER BY order_date, order_id
) AS next_order_date,
LEAD(order_date) OVER (
PARTITION BY customer_id
ORDER BY order_date, order_id
) - order_date AS gap_days
FROM orders
)
WHERE gap_days > 30
ORDER BY customer_id, order_date;The inline view is required. Analytic functions cannot appear in WHERE, because Oracle evaluates them after WHERE, GROUP BY, and HAVING. The outer query filters on the computed alias gap_days. A customer's last order has NULL for gap_days, and NULL > 30 is not true, so that row is filtered out automatically.
Notice that order_id appears as a tiebreaker in the window ORDER BY. If a customer places two orders on the same date, "next" would otherwise depend on whatever order Oracle happens to read the rows in, and the result could change between runs.
Edge cases and common errors
- Last row of a partition. It gets the default value, or
NULLif you gave none. Handle that case in downstream arithmetic.LEAD(amount) - amountisNULLon the last row, which is usually what you want for "change to next period". - Default and data type. The default must be compatible with the expression's data type. A default of
0for a date expression raises an error. Use aDATEliteral for dates and'n/a'only with character expressions. - Default is not for NULL values. The default applies only when there is no row at that offset. If the next row exists but its value is
NULL,LEADreturnsNULL, not the default. To skip such rows, useIGNORE NULLS, which is covered in a later chapter. - Offset values. An offset of 0 returns the current row's value. Negative offsets and non-integers produce an error. To look backward, use
LAG. - Missing periods.
LEADlooks at the next row that exists, not the next calendar month. If March has no row, January'sLEADreturns February's value, and February's returns April's. If you need the value for exactly the next month, first make the series dense, for example by generating the months and outer joining. - Ties in the window order. If two rows have the same
ORDER BYvalue, which one counts as "next" is arbitrary. Add a unique column to the windowORDER BY. - Different windows, different sorts. Each distinct
OVERclause can require its own sort. Reuse the samePARTITION BYandORDER BYacross several analytic functions in one query when you can, so Oracle can share the work.
Putting LEAD to work: next-period change
You can compute how much a value will change by the next period. This is the forward-looking counterpart of the month-over-month change you built with LAG.
SELECT sales_month,
amount,
LEAD(amount) OVER (ORDER BY sales_month) - amount AS change_to_next
FROM monthly_sales
ORDER BY sales_month;For the sample data, this returns 20, -30, 60, and NULL. Row N shows the same number as row N+1 would show with LAG, just shifted up by one line. Which one you pick depends on which row should "own" the difference: the period that ends it or the period that starts it.
Exercise
The table pricehistory has columns productid, valid_from, and price. Write a query that returns, for each row, the price in the next price period of the same product and the percentage increase from the current price to that next price, rounded to one decimal place. Rows with no next period should show NULL for both values.
Show answer
SELECT productid, validfrom, price, LEAD(price) OVER (PARTITION BY productid ORDER BY validfrom) AS nextprice, ROUND((LEAD(price) OVER (PARTITION BY productid ORDER BY validfrom) - price) / price * 100, 1) AS pctchange FROM pricehistory ORDER BY productid, valid_from; The PARTITION BY keeps each product's sequence separate. The last row of each product has no next row, so LEAD returns NULL and the arithmetic stays NULL. No default is given, so no special handling is needed.
Exercise
A query uses LEAD(amount, 1, 0) OVER (ORDER BY sales_month) on a table where the row for 2026-03-01 exists but has amount NULL. What does the row for 2026-02-01 show in the LEAD column, and why?
Show answer
It shows NULL. The default of 0 applies only when no row exists at the requested offset. Here the March row exists, and LEAD returns its value, which is NULL. Use IGNORE NULLS, or wrap the call in NVL, if you want 0 instead.