Sub topic 10
Looking Back with LAG
Assume you know basic SELECT, WHERE, and ORDER BY, plus inline views and the OVER clause. Oracle's LAG analytic function reads a value from an earlier row without removing the current row from the result.
How LAG works
LAG looks backward in the order defined by its window. Its basic form is:
LAG(value_expression, offset, default_value)
OVER (PARTITION BY group_column ORDER BY sort_column)| Argument | Meaning |
|---|---|
| `value_expression` | The value to read from an earlier row |
| `offset` | How many rows backward to look; the default is `1` |
| `default_value` | The value to return when no earlier row exists; the default is `NULL` |
The ORDER BY inside OVER is essential. It defines what “earlier” means. The final ORDER BY controls only the display order.
The first row has no preceding row, so LAG returns NULL unless you provide a default.
Reading previous and next values
This query compares each month's amount with its neighbours:
WITH monthly_sales AS (
SELECT DATE '2026-01-01' AS sales_month, 100 AS amount FROM dual
UNION ALL SELECT DATE '2026-02-01', 125 FROM dual
UNION ALL SELECT DATE '2026-03-01', 110 FROM dual
UNION ALL SELECT DATE '2026-04-01', 140 FROM dual
)
SELECT sales_month,
amount,
LAG(amount) OVER (
ORDER BY sales_month
) AS previous_amount,
LEAD(amount, 1, 0) OVER (
ORDER BY sales_month
) AS next_amount,
amount - LAG(amount) OVER (
ORDER BY sales_month
) AS change_from_previous
FROM monthly_sales
ORDER BY sales_month;LEAD is the forward-looking counterpart to LAG. In this example, the first LAG result is NULL, while the last LEAD result is 0 because of its default argument.
Comparing rows within groups
Use PARTITION BY when each group needs its own sequence. For example, to compare each product's sales with its previous sale:
SELECT product_id,
sale_date,
amount,
LAG(amount) OVER (
PARTITION BY product_id
ORDER BY sale_date, sale_id
) AS previous_amount
FROM product_sales
ORDER BY product_id, sale_date, sale_id;The first row for every product returns NULL. The sale_id tiebreaker makes the order deterministic when two sales have the same date.
Offsets and missing values
LAG(amount, 2) reads two rows back. A default handles the beginning of a sequence:
LAG(amount, 2, 0) OVER (ORDER BY sales_month)This returns 0 when two earlier rows do not exist. Use defaults carefully. 0 means “no earlier row” in your report, not necessarily that the earlier amount was zero.
Exercise
How would you calculate the percentage change from the previous row while avoiding division by zero?
Show answer
Use LAG in an inline view, then calculate (amount - previousamount) / NULLIF(previousamount, 0), and handle the first row where previous_amount is NULL.