Search code examples
sqlpostgresqlaggregatecoalesce

Combine two (or multiple) columns of a table


I have a table

a   b   c
1   2   
1   3   
1   4   1
2   1   2

The column a and c should be combined if the value is the same. If there are not the same, it is always so that one is empty

So the result should be:

a    b 
1    2    
1    3    
1    4
2    1

Is there any function that can be applied in PostgreSQL?


Solution

  • According to your description:

    The column a and c should be combined if the value is the same. If there are not the same, it is always so that one is empty

    all you need is an unconditional COALESCE.

    SELECT COALESCE(a, c) AS a, b FROM tbl;
    

    Assuming that by "empty" you mean NULL, not an empty string (''), in which case you'd add NULLIF:

    SELECT COALESCE(NULLIF(a, ''), c) AS a, b FROM tbl;
    

    COALESCE works for multiple parameters:

    SELECT COALESCE(a, c, d, e, f, g) AS a, b FROM tbl;