LAG And LEAD With IGNORE NULLS

Postgres 19 lets lag and lead skip nulls inside the frame with IGNORE NULLS, so gaps read as the last real observation instead of literal nulls.

SqlData Integrity

Code

snippet
-- PG 19 起排序窗口函数支持 IGNORE NULLS:先在窗口内跳过 NULL 再取偏移行
-- (first_value/last_value 的 IGNORE NULLS 见另一篇,这里演示 LAG/LEAD)
CREATE TEMP TABLE telemetry (
    taken_at time NOT NULL,
    signal   int
);

INSERT INTO telemetry VALUES
    ('09:00', 10),
    ('09:05', NULL),
    ('09:10', 20),
    ('09:15', NULL),
    ('09:20', 30);

SELECT
    taken_at,
    signal,
    -- 普通 LAG:上一个物理行,NULL 原样出现
    lag(signal) OVER w AS prev_row,
    -- IGNORE NULLS:跳过 NULL,取上一个非空读数
    lag(signal) IGNORE NULLS OVER w AS prev_non_null,
    -- LEAD 反方向同理
    lead(signal) IGNORE NULLS OVER w AS next_non_null
FROM telemetry
WINDOW w AS (ORDER BY taken_at)
ORDER BY taken_at;

Peeking at neighboring rows

The file runs SELECT / INSERT / CREATE statements, touching telemetry.

telemetry is materialized by this script itself as a session-local temp table — zero preparation, and the session end removes it.

The SQL constructs in play: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Applying it

It carries its own setup: the session-local tables in play (telemetry) come from the file’s statements — run the entire file against a disposable database.

Statements that matter

SELECT
    taken_at,
    signal,
    lag(signal) OVER w AS prev_row,
    lag(signal) IGNORE NULLS OVER w AS prev_non_null,
    lead(signal) IGNORE NULLS OVER w AS next_non_null
FROM telemetry
WINDOW w AS (ORDER BY taken_at)
ORDER BY taken_at;
INSERT INTO telemetry VALUES
    ('09:00', 10),
    ('09:05', NULL),
    ('09:10', 20),
    ('09:15', NULL),
    ('09:20', 30);
CREATE TEMP TABLE telemetry (
    taken_at time NOT NULL,
    signal   int
);

Interactive Tools for This Topic

FAQ

What are the relations in play here?
The references are `telemetry`.