Default value in select query for null values in postgres

The problem is a mismatch of datatypes; 'Missing' is text, but the product type code is numeric.

Cast the product type code to text so the two values are compatible:

select (CASE WHEN prodTypeCode IS NULL THEN
   'Missing'
    ELSE
    prodTypeCode::varchar(40)
    END) as ProductCode, SUM(amount) From sales group by prodTypeCode

See SQLFiddle.

Or, simpler:

select coalesce(prodTypeCode::varchar(40), 'Missing') ProductCode, SUM(amount)
from sales
group by prodTypeCode

See SQLFiddle.


Perhaps you have a type mismatch:

select coalesce(cast(prodTypeCode as varchar(255)), 'Missing') as ProductCode,     
       SUM(amount)
From sales s
group by prodTypeCode;

I prefer coalesce() to the case, simply because it is shorter.


I tried all 2 answers in my case and both did not work. I hope this snippet can help if both do not work for someone else:

SELECT 
COALESCE(NULLIF(prodTypeCode,''), 'Missing') AS ProductCode,        
SUM(amount)
From sales s
group by prodTypeCode;