Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005 - Using Null in a comparison

This is more of a question to satisfy my own curiosity. Given the following statement:

DECLARE @result BIT
SET @result = CASE WHEN NULL <> 4 THEN 0
                   ELSE 1
              END
PRINT @result

Why do i get back "1" instead of "0"

Changing it to:

DECLARE @result BIT
SET @result = CASE WHEN NULL IS NULL
                        OR NULL <> 4 THEN 0
                   ELSE 1
              END
PRINT @result

Correctly gives me back "0"

I know NULL comparisons can be tricky, but this particular example slipped through our code review process.

Any clarifications would be greatly appreciated

like image 955
Jim B Avatar asked Dec 22 '22 02:12

Jim B


2 Answers

This is because of 3 valued logic. In the first case Unknown does not evaluate to true so you end up in the else

DECLARE @result BIT
SET @result = CASE WHEN Unknown THEN 0
                   ELSE 1
              END
PRINT @result

In the second case you are doing True or Unknown which evaluates to true.

DECLARE @result BIT
SET @result = CASE WHEN True
                        OR Unknown THEN 0
                   ELSE 1
              END
PRINT @result
like image 154
Martin Smith Avatar answered Dec 29 '22 13:12

Martin Smith


This is due to the ANSI SQL standard and the behavior of comparison operators with NULL. Whenever you want to compare a value with a value that could be NULL, you need to use the IS operator to explicitly check for the case where the value could be NULL. Or you can disable the ANSI_NULLS option in SQL Server.

The following examples do what you want:

DECLARE @result BIT  
DECLARE @input INT

SET @input = NULL
SET @result = CASE WHEN (@input IS NULL OR @input <> 4) THEN 0  
                   ELSE 1  
              END  
PRINT @result  

Or this:

SET ANSI_NULLS OFF

DECLARE @result BIT 
SET @result = CASE WHEN NULL <> 4 THEN 0 
                   ELSE 1 
              END 
PRINT @result 

References:

http://msdn.microsoft.com/en-us/library/ms188048.aspx

like image 38
luksan Avatar answered Dec 29 '22 13:12

luksan