Home > Software engineering >  Postgresql : get notnull column value alone in select statement
Postgresql : get notnull column value alone in select statement

Time:01-02

I have a table as below

Id String Numeric Date
1 null 1006 null
2 Testing value null null
3 null null 1-1-2023

Id, String, Numeric, Date are the column names. Id is the primary key. Id is going to have only one value (either string or numeric or date).

How to I get single value for single Id using select query leaving null values of other respective columns

I tried

select String OR Numeric OR Date 
from Table t 
where id = '2';

CodePudding user response:

You could use the coalesce function to do this

select COALESCE(String, Numeric::text, Date::text) 
from Table t 
where id = '2';

This will give back the first non-null value out of the three columns or null if all three columns are null. The output of this query is a string however, so depending on your application you might have the recast the result back again later. You could also consider using a case instead

SELECT
    CASE WHEN string IS NOT NULL THEN string
         WHEN numeric IS NOT NULL THEN numeric::string
         WHEN date IS NOT NULL THEN date::string 
         ELSE NULL 
    END 
FROM
    Table t 
WHERE
    id = '2';

This will get very messy when there are lots of columns so I wouldn't recommend it in general, but it does allow for some extra flexibility on the output if required.

  • Related