Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle NULLs in a DATEDIFF comparison?

Tags:

sql

tsql

datediff

I have to compare 2 separate columns to come up with the most recent date between them. I am using DATEDIFF(minute, date1, date2) to compare them, however, in some records the date is Null, which returns a null result and messes up the CASE.

Is there a way around this, or a way to predetermine which date is null up front?

(psudocode)

UPDATE TABLE
SET NAME = p.name,
    NEW_DATE = CASE WHEN DATEDIFF(minute,d.date1,d.date2) <= 0 THEN d.date
                    ELSE d.date2
               END
FROM TABLE2 d
INNER JOIN TABLE3 p
  ON d.ACCTNUM = p.ACCTNUM
like image 702
user1385330 Avatar asked May 09 '12 18:05

user1385330


People also ask

What are the rules to be applied to NULLs whilst doing comparisons?

The same is true for any comparisons with NULL under the ANSI Standard; whether you are comparing NULL to a CHAR, INT or any other value, variable or table column. Rule #2: In ANSI SQL, NULL is not equal to anything, even other NULLs! Comparisons with NULL always result in UNKNOWN.

Why does datediff return NULL?

DATEDIFF() With Wrong Date ValuesIf either of the date in the DATEDIFF() function is wrong or invalid, then the DATEDIFF() function returns NULL.

Can we compare NULL with NULL?

SQL Server IS NULL / IS NOT NULL Because the NULL value cannot be equal or unequal to any value, you cannot perform any comparison on this value by using operators such as '=' or '<>'.

What can you replace NULLs with?

Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0.


1 Answers

You can just add extra logic into your CASE:

UPDATE TABLE 
SET NAME = p.name, 
    NEW_DATE = CASE 
                    WHEN d.date1 IS NULL THEN -- somewhat 
                    WHEN d.date2 IS NULL THEN -- somewhat 
                    WHEN DATEDIFF(minute,d.date1,d.date2) <= 0 THEN d.date 
                    ELSE d.date2 
               END 
FROM TABLE2 d 
INNER JOIN TABLE3 p 
  ON d.ACCTNUM = p.ACCTNUM 
like image 184
Andrey Gurinov Avatar answered Sep 19 '22 10:09

Andrey Gurinov