0

Is it possible to use COALESCE (or any other way) to replace NULL values from a TIMESTAMP column with a string like 'N/A'?

In my SELECT statement I have a

CASE WHEN n.expiration_date::date IS NULL THEN 'N/A' ELSE n.expiration_date::date END

When I try this, I get this error, which makes sense:

invalid input syntax for type date: "N/A"

I found this blog post too about this problem. Is there a way around it?

Vinayak
  • 1,103
  • 3
  • 18
  • 40

1 Answers1

5

All values of a CASE expression have to evaluate to the same data type.

If you really need the N/A, you need to convert the date to a character type:

CASE 
    WHEN n.expiration_date IS NULL THEN 'N/A' 
    ELSE n.expiration_date::date::text 
END

Or if you want to have control over the format:

CASE 
    WHEN n.expiration_date IS NULL THEN 'N/A' 
    ELSE to_char(n.expiration_date, 'YYYY-MM-DD')
END
  • That's what I did. Thanks! Related: https://stackoverflow.com/questions/43899262/using-coalesce-with-different-data-types – Vinayak May 09 '19 at 11:47