sqlsql-serverisnull

comparison with NULL date gives NULL value in SQL Server


This code results in NULL. sale_jan_dt and sale_feb_dt both datetime columns.

s.sale_feb_dt = 2022-09-01 01:19:00.000
s.sale_jan_dt = NULL

select
    case 
        when s.sale_jan_dt >= s.sale_feb_dt
            then cast(convert(char(20), s.sale_feb_dt, 20) as datetime)             
        else
            cast(convert(char(20), s.sale_jan_dt, 20) as datetime) 
    end as min_sales_month
from sales s

Would this code return a datetime value or string? I have to use the min_sales_month in date calculations.

select
    case 
        when isnull(s.sale_jan_dt, '2100-12-31 23:59:59') >= s.sale_feb_dt
            then cast(convert(char(20), s.sale_feb_dt, 20) as datetime) 
            else cast(convert(char(20), s.sale_jan_dt, 20) as datetime) 
    end as min_sales_month
from 
    sales s

Solution

  • You can change comparison, swap result, and I believe you'll get what you want.

    select
        case 
            when s.sale_jan_dt >= s.sale_feb_dt or s.sale_jan_dt is null
                then cast(convert(char(20), s.sale_feb_dt, 20) as datetime)             
            else
                cast(convert(char(20), s.sale_jan_dt, 20) as datetime) 
        end as min_sales_month
    from sales s