skip to Main Content

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


  1. Use greatest() which is NULL safe:

    select greatest(date1, date2) as higher_date
    from the_table
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search