Consider a type table 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 queries that replace each NULL value in column_a last non- NULL from the previous column values ββin the order specified by column_order . The result should look like this:
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 zero. The following works if there is at most one NULL value:
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 can achieve the results above? Is there an efficient query that scales well for a large number of rows?
Marco source share