Consider a table like with the following data
column_a (boolean) | column_order (integer)
TRUE | 1
NULL | 2
NULL | 3
TRUE | 4
NULL | 5
FALSE | 6
NULL | 7
I would like to write a queries that replaces each NULL
value in column_a
with the last non-NULL
value out of the previous values of the column according to the order specified by column_order
The result should look like:
column_a (boolean) | column_order (integer)
TRUE | 1
TRUE | 2
TRUE | 3
TRUE | 4
TRUE | 5
FALSE | 6
FALSE | 7
For simplicity, we can assume that the first value is never null. The following works if there are no more than one consecutive NULL
values:
SELECT
COALESCE(column_a, lag(column_a) OVER (ORDER BY column_order))
FROM test_table
ORDER BY column_order;
However, the above does not work for an arbitrary number of consecutive NULL
values. What is a Postgres query that is able to achieve the results above? Is there an efficient query that scales well to a large number of rows?