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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With