Sub topic 11
Looking Ahead with LEAD
Prerequisites and working model
This chapter assumes you can write basic Oracle SELECT statements and understand WHERE and ORDER BY. You should also know how an analytic function uses an OVER clause to calculate a value for each result row without grouping rows together.
LEAD is an analytic function that reads a value from a later row in the window. It is useful when the current row needs to be compared with the next event, date, price, or measurement.
LAG looks backward. LEAD looks forward.
Basic LEAD syntax
The basic form is:
LEAD(value_expression, offset, default_value)
OVER (
[PARTITION BY group_columns]
ORDER BY ordering_columns
)value_expressionis the column or expression to read from a later row.offsetsays how many rows forward to look. It defaults to1.default_valueis returned when no later row exists. Without a default, Oracle returnsNULL.ORDER BYdefines what “later” means.
For example, this query reads the next month's sales amount:
SELECT sales_month,
amount,
LEAD(amount) OVER (
ORDER BY sales_month
) AS next_amount
FROM monthly_sales
ORDER BY sales_month;For the January row, next_amount is February's amount. For the final month, there is no next row, so the result is NULL.
Looking ahead within groups
Use PARTITION BY when each group must have its own sequence. The function does not look into the next department, customer, or account.
SELECT department_id,
employee_id,
hire_date,
LEAD(hire_date) OVER (
PARTITION BY department_id
ORDER BY hire_date, employee_id
) AS next_hire_date
FROM employees
ORDER BY department_id, hire_date, employee_id;Here, next_hire_date is the next hire date within the same department. The last employee in each department receives NULL.
The extra employee_id column makes the ordering deterministic when two employees share the same hire_date. Without a tiebreaker, Oracle can choose either tied row as the next row.
Offsets and defaults
This query looks two rows ahead and returns 0 when that row does not exist:
SELECT sales_month,
amount,
LEAD(amount, 2, 0) OVER (
ORDER BY sales_month
) AS amount_two_months_ahead
FROM monthly_sales
ORDER BY sales_month;The default value should be compatible with the value expression. For numeric amounts, use a numeric default such as 0. For dates or text, use a suitable value of the matching type.
LEAD can also support a period comparison:
SELECT sales_month,
amount,
LEAD(amount) OVER (ORDER BY sales_month) - amount AS change_to_next
FROM monthly_sales
ORDER BY sales_month;The final row produces NULL because its next amount is NULL.
Exercise
How would you return the next order date for each customer, ordered by order date and order_id?
Show answer
Use LEAD(orderdate) OVER (PARTITION BY customerid ORDER BY orderdate, orderid).