Sub topic 12
Offset and default arguments
Earlier chapters used LAG(amount) and LEAD(amount) with one argument. Both functions take up to three arguments, and the second and third change what a query returns, especially at the edges of a partition. This chapter assumes you can write an OVER clause with PARTITION BY and ORDER BY, and that you have used LAG and LEAD in their basic form.
The full signature
LAG (value_expr [, offset [, default]]) [RESPECT NULLS | IGNORE NULLS]
OVER ([PARTITION BY ...] ORDER BY ...)
LEAD (value_expr [, offset [, default]]) [RESPECT NULLS | IGNORE NULLS]
OVER ([PARTITION BY ...] ORDER BY ...)| Argument | Meaning | If omitted |
|---|---|---|
| `value_expr` | The column or expression read from the other row | Required |
| `offset` | How many rows to move from the current row | 1 |
| `default` | Value returned when the target row does not exist | `NULL` |
LAG moves backward in the window ordering and LEAD moves forward. Everything else about the two functions is identical, so the rules below apply to both.
Unlike the ranking functions, LAG and LEAD require an ORDER BY inside OVER. Without an order, "previous row" has no meaning.
Offset: how far to look
The offset is a non-negative integer. Typical uses:
LAG(amount, 1)is the previous row. This is the same asLAG(amount).LAG(amount, 12)is the row twelve positions back. With one row per month, that is the same month last year.LEAD(amount, 3)is the row three positions ahead.- An offset of 0 returns the current row's own value. This is rarely useful.
The offset can be a literal or a bind variable, so a report can let the user choose the comparison distance. A negative offset is an error. To look in the other direction, switch between LAG and LEAD.
The offset counts rows, not units of time or value. If a month is missing from the data, LAG(amount, 12) does not return the same month last year. It returns whatever row is twelve positions back. When gaps are possible, first generate a complete calendar and outer join your data to it, or use a self-join on the date.
Default: what to return past the edge
For the first row in a partition, LAG has nothing to read. For the last row, LEAD has nothing to read. In general, any row whose target position falls outside the partition gets the default. If you give no default, that value is NULL.
The default must be compatible with the datatype of value_expr. If value_expr is a DATE, a default of 0 is an error. Use a date, such as DATE '1900-01-01', instead.
The default can also be an expression, including a column from the current row. LAG(amount, 1, amount) returns the row's own amount when there is no previous row.
Defaults apply per partition
With PARTITION BY, each partition has its own first and last row. The default is used at the start of every partition, not just once for the whole result.
The default does not replace stored NULLs
This is the most common mistake. The default is used only when the target row is missing. If the target row exists but its value is NULL, you get NULL, not the default.
A worked example
This script creates a small table with a NULL amount in the middle of one region:
CREATE TABLE region_sales (
region VARCHAR2(10),
sales_month DATE,
amount NUMBER
);
INSERT ALL
INTO region_sales VALUES ('EAST', DATE '2026-01-01', 100)
INTO region_sales VALUES ('EAST', DATE '2026-02-01', 120)
INTO region_sales VALUES ('EAST', DATE '2026-03-01', NULL)
INTO region_sales VALUES ('EAST', DATE '2026-04-01', 150)
INTO region_sales VALUES ('WEST', DATE '2026-01-01', 80)
INTO region_sales VALUES ('WEST', DATE '2026-02-01', 90)
INTO region_sales VALUES ('WEST', DATE '2026-03-01', 95)
SELECT * FROM dual;
COMMIT;Now compare three variants side by side:
SELECT region,
TO_CHAR(sales_month, 'YYYY-MM') AS month,
amount,
LAG(amount) OVER (PARTITION BY region ORDER BY sales_month) AS lag1,
LAG(amount, 2) OVER (PARTITION BY region ORDER BY sales_month) AS lag2,
LAG(amount, 1, 0) OVER (PARTITION BY region ORDER BY sales_month) AS lag1_def0
FROM region_sales
ORDER BY region, sales_month;The result:
| REGION | MONTH | AMOUNT | LAG1 | LAG2 | LAG1_DEF0 |
|---|---|---|---|---|---|
| EAST | 2026-01 | 100 | NULL | NULL | 0 |
| EAST | 2026-02 | 120 | 100 | NULL | 100 |
| EAST | 2026-03 | NULL | 120 | 100 | 120 |
| EAST | 2026-04 | 150 | NULL | 120 | NULL |
| WEST | 2026-01 | 80 | NULL | NULL | 0 |
| WEST | 2026-02 | 90 | 80 | NULL | 80 |
| WEST | 2026-03 | 95 | 90 | 80 | 90 |
Read the table in three steps:
- With offset 2, the first two rows of each region have no target row.
lag2isNULLfor both, and the count restarts at WEST in January. lag1_def0is 0 in January for both regions, so the default is applied once per partition.- For EAST in April,
lag1_def0is stillNULL. The previous row (March) exists, and its stored amount isNULL. The default of 0 does not apply.
The diagram shows how LAG decides what to return.
Choosing a default deliberately
A default of 0 is convenient but can distort calculations. Consider a month-over-month change:
SELECT region,
sales_month,
amount,
amount - LAG(amount, 1, 0) OVER (PARTITION BY region ORDER BY sales_month) AS change_bad,
amount - LAG(amount) OVER (PARTITION BY region ORDER BY sales_month) AS change_null,
amount - LAG(amount, 1, amount) OVER (PARTITION BY region ORDER BY sales_month) AS change_zero
FROM region_sales
ORDER BY region, sales_month;For the first month of each region:
change_badequals the full amount, as if sales jumped from nothing. That is usually wrong.change_nullisNULL, which says "no comparison is possible."change_zerois 0, which says "no change." This is appropriate only if your report should show zero there.
Pick the option that matches the business meaning, and keep in mind that a NULL stored amount (EAST in March) makes the change NULL in all three versions.
Interaction with IGNORE NULLS
Adding IGNORE NULLS changes how rows are counted. The function skips rows whose value_expr is NULL, and the offset counts only non-NULL rows:
SELECT region,
TO_CHAR(sales_month, 'YYYY-MM') AS month,
amount,
LAG(amount, 1, 0) IGNORE NULLS
OVER (PARTITION BY region ORDER BY sales_month) AS last_known
FROM region_sales
WHERE region = 'EAST'
ORDER BY sales_month;| REGION | MONTH | AMOUNT | LAST_KNOWN |
|---|---|---|---|
| EAST | 2026-01 | 100 | 0 |
| EAST | 2026-02 | 120 | 100 |
| EAST | 2026-03 | NULL | 120 |
| EAST | 2026-04 | 150 | 120 |
April now returns 120, the nearest earlier non-NULL value. The default of 0 appears only in January, where no earlier non-NULL row exists. RESPECT NULLS is the default behavior and gives the results shown earlier.
Common errors
- Expecting the default to fill stored NULLs. Wrap the whole call in
NVLorCOALESCEif you want that, or useIGNORE NULLSto skip them. - Mixing datatypes. The default must match the type of
value_expr. - Using row counts as time distances. Missing periods shift every later comparison.
- Forgetting that partitions reset. An offset larger than the partition size returns the default for every row in that partition.
- Nesting analytic functions. You cannot use another analytic function as
value_expr. Compute it in an inline view first, then applyLAGin the outer query.
Exercise
A table readings(sensor_id, reading_time, value) has hourly rows per sensor. Write a query that returns, for each row, the value from two hours earlier in the same sensor, or -1 if the sensor has no such earlier row. What does the query return for a row whose value two rows back exists but is NULL?
Show answer
SELECT sensorid, readingtime, value, LAG(value, 2, -1) OVER (PARTITION BY sensorid ORDER BY readingtime) AS twoback FROM readings ORDER BY sensorid, reading_time; For a row whose target row exists but holds a NULL value, the query returns NULL, not -1. The default -1 appears only for the first two rows of each sensor, where no target row exists. Add IGNORE NULLS if you want the offset to count only non-NULL readings.