postgresql Select higher Timestamp with Null Values

Viewed 24

The problem is if i compare two timestamps and one of them is NULL it chooses Null as higher Value.

SELECT case 
         when "Date1" < "Date2" then "Date1" 
         else "Date2"  
       end as "HigherDate"
FROM "table"

How can i select always the higher date between those two even if one of them is NULL?

2 Answers

Use greatest() which is NULL safe:

select greatest(date1, date2) as higher_date
from the_table

You can use COALESCE.

SELECT case when COALESCE("Date1", ConstantLowerDate) < COALESCE("Date2", ConstantHigherDate) then "Date1" else "Date2" end as "HigherDate" FROM "table"

Where ConstantLowerDate is a fixed date always lower what all Date2 possible values and ConstantHigherDate always high what Date1. Attention: If Date1 and Date2 are null will return ConstantLowerDate

Related