Sub topic 15
Skipping NULLs with `IGNORE NULLS`
Assume you know basic SELECT, ORDER BY, GROUP BY, and inline views. This chapter focuses on Oracle's LAG and LEAD functions when some values are missing.
Why NULL handling matters
LAG reads a value from an earlier row, and LEAD reads a value from a later row. By default, both functions use RESPECT NULLS. That means a NULL value is treated as the value at that position.
IGNORE NULLS changes the lookup. Oracle skips rows where the expression being read is NULL and finds the nearest non-NULL value instead.
WITH sensor_readings (reading_time, reading) AS (
SELECT TIMESTAMP '2026-01-01 10:00:00', 20 FROM dual UNION ALL
SELECT TIMESTAMP '2026-01-01 11:00:00', NULL FROM dual UNION ALL
SELECT TIMESTAMP '2026-01-01 12:00:00', NULL FROM dual UNION ALL
SELECT TIMESTAMP '2026-01-01 13:00:00', 23 FROM dual UNION ALL
SELECT TIMESTAMP '2026-01-01 14:00:00', 25 FROM dual
)
SELECT reading_time,
reading,
LAG(reading) OVER (
ORDER BY reading_time
) AS previous_reading_respect,
LAG(reading) IGNORE NULLS OVER (
ORDER BY reading_time
) AS previous_reading_ignore
FROM sensor_readings
ORDER BY reading_time;The result is conceptually:
| Reading time | Reading | Respect NULLS | IGNORE NULLS |
|---|---|---|---|
| 10:00 | 20 | NULL | NULL |
| 11:00 | NULL | 20 | 20 |
| 12:00 | NULL | NULL | 20 |
| 13:00 | 23 | NULL | 20 |
| 14:00 | 25 | 23 | 23 |
At 13:00, RESPECT NULLS returns the value at 12:00, which is NULL. IGNORE NULLS skips the missing readings at 11:00 and 12:00, then returns 20 from 10:00.
How the lookup works
For LAG, Oracle searches backward in the window order. For LEAD, it searches forward. The offset counts qualifying values when IGNORE NULLS is used.
You can also provide an offset and a fallback value. The following asks for the second earlier non-NULL reading and returns -1 when that value does not exist.
SELECT reading_time,
reading,
LAG(reading, 2, -1) IGNORE NULLS OVER (
ORDER BY reading_time
) AS second_previous_reading
FROM sensor_readings
ORDER BY reading_time;The default value applies when the requested offset cannot be found. It does not replace a stored NULL when RESPECT NULLS finds one.
Common errors
RESPECT NULLSis the default, so omitting the clause does not skip missing values.IGNORE NULLSapplies to the expression passed toLAGorLEAD, not to the ordering column.- Use a deterministic ordering. If two rows have the same timestamp, add a unique column such as
reading_id. - A skipped
NULLis different from a genuine zero.IGNORE NULLSskips onlyNULL, not 0.
Exercise
Which value does LAG(reading) IGNORE NULLS return for a row whose reading is 23, when the preceding readings are 20, NULL, and NULL?
Show answer
It returns 20, because Oracle skips the two NULL readings and finds the nearest earlier non-NULL value.