Search code examples
performancepostgresqlsql-tuningquery-tuning

How to select id, first_not_null(value1), first_not_null(value2).. on Postgresql


I have a table like this:

+--+---------+---------+
|id|str_value|int_value|
+--+---------+---------+
| 1| 'abc'   |         |
| 1|         |    1    |
| 2| 'abcd'  |         |
| 2|         |    2    |
+--+---------+---------+

I need to get this:

+--+---------+---------+
|id|str_value|int_value|
+--+---------+---------+
| 1| 'abc'   |    1    |
| 2| 'abcd'  |    2    |
+--+---------+---------+

It seems to me that I need something like:

select id, first_not_null(str_value), first_not_null(int_value)
from table
group by id

Is there any acceptable way to do this? I use Postgresql 9.0.1.

Update: this should work with uuid types as well


Solution

  • You should look at http://www.postgresql.org/docs/8.1/static/functions-aggregate.html for aggregate functions.

    I guess max should do the work

    EDIT: Working example

    select id, max(col1), max(col2) from (
        select 1 as id, null as col1, 'test' as col2
        union 
        select 1 as id ,'blah' as col1, null as col2
    )  x group by id