SQL IGNORE NULLS in window functions
A modifier on offset functions that skips NULLs: LAST_VALUE(x IGNORE NULLS) returns the most recent non-NULL value instead of the literal last row's value.
- Categoria
- Janela
- Returns
type of the expression- In this category
- 17 of 79
Sintaxe
LAST_VALUE(x) IGNORE NULLS OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) | LAG(x) IGNORE NULLS OVER (ORDER BY id)
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | SQL Server 2022+ (and Azure SQL) for LAG, LEAD, FIRST_VALUE, LAST_VALUE |
| PostgreSQL | Not built in | not supported through PostgreSQL 18; emulate with the COUNT/MAX trick |
| MySQL | Not built in | parsed but refused ('doesn't yet support IGNORE NULLS'); emulate |
| SQLite | Not built in | not supported; emulate with the COUNT/MAX trick |
| Oracle | Sim | FIRST_VALUE, LAST_VALUE, NTH_VALUE, LAG and LEAD |
Exemplos
Oracle
SELECT day, price,
LAST_VALUE(price IGNORE NULLS) OVER (
ORDER BY day
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS last_known
FROM prices;
Any engine
-- portable forward fill: carry the last non-NULL price
WITH marked AS (
SELECT p.*, COUNT(price) OVER (ORDER BY day) AS grp
FROM prices p
)
SELECT day,
MAX(price) OVER (PARTITION BY grp) AS price_ffill
FROM marked;
Bom saber
- Placement: SQL Server accepts IGNORE NULLS only after the closing parenthesis, LAST_VALUE(x) IGNORE NULLS OVER (...). Oracle accepts that form and also LAST_VALUE(x IGNORE NULLS). Write it after the parenthesis and the query runs on both.
- The portable emulation is two windows: COUNT(x) OVER (ORDER BY id) only advances on non-NULL rows, so it gives each NULL run the same number as the value before it; MAX(x) OVER (PARTITION BY that number) then carries the value across the run.
- LAG(x) IGNORE NULLS returns the previous non-NULL value, however far back. FIRST_VALUE and LAST_VALUE still obey the frame: for forward fill, end the frame at CURRENT ROW; ending it at UNBOUNDED FOLLOWING returns the partition's final non-NULL value on every row.
Questions about IGNORE NULLS
How do I forward-fill NULLs in PostgreSQL or MySQL?
COUNT(price) OVER (ORDER BY day) gives every NULL row the same number as the last non-NULL row before it; MAX(price) OVER (PARTITION BY that number) copies the value down. It runs on all five engines. NULLs before the first value stay NULL.
Did SQL Server always support IGNORE NULLS?
No. SQL Server 2019 and earlier reject the keyword on all four functions; use the COUNT/MAX emulation there.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.