Having the following data (blank means NULL):
ID ColA ColB ColC
1 15 20
2 11 4
3 3
How can I get the last not-NULL values of each column in a single query? So the resulting for the given data would be:
ColA ColB ColC
11 3 20
I have not found much, the function that seemed to do something similar to what I describe was COALESCE
, but it does not work as expected in my case.
Looks like you would have to run a separate query per column with plain SQL. For a small table and only 3 columns, @Guffa's query should be fine.
3 window functions
You can do the same in one query with three window functions: Not sure if this is faster than three individual subqueries:
count()
as window functionYou can also exploit the fact that
count()
does not countNULL
values.For bigger tables and more columns, a recursive CTE or a procedural function will be considerably faster:
Recursive CTE
PL/pgSQL function
My money is on this one for best performance:
Call:
Test with
EXPLAIN ANALYZE
. Would be nice if you could come back with a comparison of the solutions.You can use subqueries: