Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return column name with coalesce

Tags:

sql

postgresql

I want to select first not null value from several columns in my table. Usually I would use

SELECT COALESCE(col1, col2, col3) FROM table

but this time I don't need value, but name of column (or some specified text for every column) with first not null value.

An example:

Table:

col1 | col2 | col3
null | null | 3
null | 5    | 8
2    | null | 2

should return:

col3
col2
col1

Is there any way to do it with single SQL statement?

Note: I'm using PostgreSQL.

like image 426
Lidia B. Avatar asked Oct 17 '14 11:10

Lidia B.


1 Answers

I would suggest to use CASE statement

SELECT 
   CASE WHEN col1 IS NOT NULL THEN 'col1'
        WHEN col2 IS NOT NULL THEN 'col2'
        WHEN col3 IS NOT NULL THEN 'col3'
        ELSE NULL
   END
FROM table;
like image 178
Nailgun Avatar answered Oct 22 '22 13:10

Nailgun