Pages

Social Icons

Thursday 22 December 2011

Difference between != NULL and IS NOT NULL


When you deal with NULL in SQL Server you basically work with 3-value logic with all the implications.

IF(@myVar != null)  vs  IF(@myVar is not null)

It basically boils down to the question

what is the difference between: @myVar = null vs @myVar is null

@myVar = null will always evaluate to null as what you are asking is: is the value in @myVar equal to UNKNOWN

As you do not know what the UNKNOWN is this question cannot by answered yes, or no so it evaluates to UNKNOWN

e.g.
    "is 1 = UNKNOWN" - I do not know
    "is 'a' = UNKNOWN" - I do not know
    "is UNKNOWN = UNKNOWN" - I do not know

The last one may be a bit tricky but just imagine that you have 2 boxes with candy and you do not know neither how many candy are in box1 one nor in box2 so asking.
so the answer is I do not know

the second one @myVar is null is different as it is like asking is the value in @myVar UNKNOWN

so the difference is that you specifically ask "is it true that the value stored in the variable is UNKNOWN?", so
    "is 1 UNKNOWN" - NO
    "is 'a' UNKNOWN" - NO
    "is UNKNOWN UNKNOWN" - YES

THX,
RS

No comments:

Post a Comment