Sub topic 10
Looking back with LAG
LAG is an analytic function that returns a column value from an earlier row in the same ordered result set. It does this without a self-join. This chapter assumes you can write an OVER clause with PARTITION BY and ORDER BY. It also assumes you know how ROW_NUMBER orders rows inside a partition. Here you will use those pieces to compare each row with the one before it.
What LAG does
For each row, LAG finds the row that comes before it in the window ordering. It returns the value of an expression from that earlier row. The query keeps every row, as with other analytic functions.
The syntax is:
LAG(value_expression [, offset [, default]])
[RESPECT NULLS | IGNORE NULLS]
OVER ([PARTITION BY ...] ORDER BY ...)This chapter uses only the first argument. Later chapters cover offset and default, and IGNORE NULLS. With one argument, LAG looks back exactly one row and returns NULL when no earlier row exists.
Three rules shape every LAG query:
ORDER BYinsideOVERis required. "Previous" has no meaning without an order, and Oracle raises an error if you leave it out.PARTITION BYis optional. Without it, the whole result set is one partition.- You cannot add a windowing clause such as
ROWS BETWEEN.LAGalways works by row position.
Setting up sample data
The examples use a small sales table. Run this first.
CREATE TABLE monthly_sales (
sales_month DATE,
amount NUMBER(10,2)
);
INSERT INTO monthly_sales VALUES (DATE '2026-01-01', 100);
INSERT INTO monthly_sales VALUES (DATE '2026-02-01', 120);
INSERT INTO monthly_sales VALUES (DATE '2026-03-01', 90);
INSERT INTO monthly_sales VALUES (DATE '2026-04-01', 150);
COMMIT;A first LAG query
SELECT sales_month,
amount,
LAG(amount) OVER (ORDER BY sales_month) AS prev_amount
FROM monthly_sales
ORDER BY sales_month;| SALES_MONTH | AMOUNT | PREV_AMOUNT |
|---|---|---|
| 2026-01-01 | 100 | NULL |
| 2026-02-01 | 120 | 100 |
| 2026-03-01 | 90 | 120 |
| 2026-04-01 | 150 | 90 |
Oracle sorts the rows by sales_month for the window calculation. Each row then receives the amount of the row directly above it. January has no earlier row, so its prev_amount is NULL.
Two ORDER BY clauses
The query above has two separate ORDER BY clauses. They do different jobs.
- The one inside
OVERdecides which row counts as "previous". It does not guarantee the order of the final output. - The one at the end of the query sorts the result you see.
Oracle often returns rows in window order, but you should not rely on that. Repeat the sort at the end of the query whenever the display order matters.
Using LAG inside calculations
Because LAG returns an ordinary value, you can use it in expressions. The month-over-month change is the current amount minus the previous one.
SELECT sales_month,
amount,
amount - LAG(amount) OVER (ORDER BY sales_month) AS change_from_prev
FROM monthly_sales
ORDER BY sales_month;For the sample data the changes are NULL, 20, -30, and 60. Any arithmetic that involves NULL gives NULL, so the first row stays NULL instead of showing a misleading value. Handle that case in the report with NVL or COALESCE only if you really want a number there.
Restarting the look-back for each group
Add PARTITION BY when the data contains several independent series. LAG then restarts in every partition, and the first row of each partition gets NULL. This stops a row from one group borrowing a value from another.
CREATE TABLE regional_sales (
region VARCHAR2(10),
sales_month DATE,
amount NUMBER(10,2)
);
INSERT INTO regional_sales VALUES ('East', DATE '2026-01-01', 100);
INSERT INTO regional_sales VALUES ('East', DATE '2026-02-01', 120);
INSERT INTO regional_sales VALUES ('East', DATE '2026-03-01', 90);
INSERT INTO regional_sales VALUES ('West', DATE '2026-01-01', 50);
INSERT INTO regional_sales VALUES ('West', DATE '2026-02-01', 40);
INSERT INTO regional_sales VALUES ('West', DATE '2026-03-01', 70);
COMMIT;
SELECT region,
sales_month,
amount,
LAG(amount) OVER (
PARTITION BY region
ORDER BY sales_month
) AS prev_amount
FROM regional_sales
ORDER BY region, sales_month;West's January row shows NULL, not East's March value of 90. Without the PARTITION BY, the rows would be treated as one sequence, and the first West row would look back at the last East row. The result would have no error and no warning, only wrong numbers.
Filtering on a LAG result
Analytic functions are allowed only in the SELECT list and in the query's final ORDER BY. You cannot write WHERE amount < LAG(amount) OVER (...). Oracle evaluates the WHERE clause before analytic functions run, so the previous-row value does not exist yet. Compute it in an inline view and filter in the outer query, as you did with ROW_NUMBER.
SELECT sales_month, amount, prev_amount
FROM (
SELECT sales_month,
amount,
LAG(amount) OVER (ORDER BY sales_month) AS prev_amount
FROM monthly_sales
)
WHERE amount < prev_amount
ORDER BY sales_month;This returns only March, the one month where sales fell. January is excluded because amount < NULL is not true.
Common errors and gotchas
Missing ORDER BY. LAG(amount) OVER () and LAG(amount) OVER (PARTITION BY region) both fail with an error, because an analytic LAG needs an ordering.
Ties in the ordering column. If two rows in a partition have the same ORDER BY value, Oracle can place them in either order. "Previous" then becomes ambiguous, and results may change between runs or after a plan change. Add a tiebreaker, such as a unique ID, at the end of the window ORDER BY, as you did for ROW_NUMBER.
LAG(amount) OVER (ORDER BY sales_month, sale_id)Gaps in the data. LAG counts rows, not calendar units. If February is missing, March's prev_amount is January's value, and nothing flags the gap. A "month-over-month" figure is then really "versus the previous row that exists". If gaps are possible, either fill them first with a calendar table or compare the dates as well, for example by returning LAG(sales_month) next to the amount.
NULL values in the data. LAG returns a NULL from an earlier row as is. A NULL result can therefore mean "no previous row" or "the previous row's value was NULL". The two cases look identical in the output. The IGNORE NULLS option, covered later, changes this behavior.
Wrong sort direction. LAG follows the direction you give. With ORDER BY sales_month DESC, the "previous" row is the one with the later date. Nothing is wrong with the function, but the result may not be what you meant.
Comparison with a self-join
Before analytic functions, you would compare a row with its predecessor by joining the table to itself on a computed condition such as ADD_MONTHS(a.sales_month, -1) = b.sales_month. LAG has these advantages:
- It reads the table once instead of twice.
- It does not require a join key that "points" at the previous row.
- It handles partitions with a single clause.
The self-join, however, has different semantics. It matches a specific calendar month and returns nothing when that month is absent. LAG takes whichever row precedes. Choose based on which behavior your report requires.
Exercise
A table orders(customer_id, order_date, total) holds several orders per customer. Write a query that returns each order with the total of the same customer's previous order, and the difference between the two. What does the first order of each customer show, and why? Add a column to the window ordering so the result is deterministic if a customer places two orders on the same date, assuming a unique order_id column exists.
Show answer
SELECT customerid, orderid, orderdate, total, LAG(total) OVER (PARTITION BY customerid ORDER BY orderdate, orderid) AS prevtotal, total - LAG(total) OVER (PARTITION BY customerid ORDER BY orderdate, orderid) AS changefromprev FROM orders ORDER BY customerid, orderdate, orderid; The first order of each customer shows NULL in both prevtotal and changefromprev, because no earlier row exists in that customer's partition. The order_id tiebreaker makes the "previous" row well defined when two orders share a date.