Why does NULL = NULL evaluate to false in SQL server

前端 未结 19 1566
一向
一向 2020-11-22 05:02

In SQL server if you have nullParam=NULL in a where clause, it always evaluates to false. This is counterintuitive and has caused me many errors. I do understa

19条回答
  •  情深已故
    2020-11-22 05:49

    At technet there is a good explanation for how null values work.

    Null means unknown.

    Therefore the Boolean expression

    value=null

    does not evaluate to false, it evaluates to null, but if that is the final result of a where clause, then nothing is returned. That is a practical way to do it, since returning null would be difficult to conceive.

    It is interesting and very important to understand the following:

    If in a query we have

    where (value=@param Or @param is null) And id=@anotherParam
    

    and

    • value=1
    • @param is null
    • id=123
    • @anotherParam=123

    then

    "value=@param" evaluates to null
    "@param is null" evaluates to true
    "id=@anotherParam" evaluates to true

    So the expression to be evaluated becomes

    (null Or true) And true

    We might be tempted to think that here "null Or true" will be evaluated to null and thus the whole expression becomes null and the row will not be returned.

    This is not so. Why?

    Because "null Or true" evaluates to true, which is very logical, since if one operand is true with the Or-operator, then no matter the value of the other operand, the operation will return true. Thus it does not matter that the other operand is unknown (null).

    So we finally have true=true and thus the row will be returned.

    Note: with the same crystal clear logic that "null Or true" evaluates to true, "null And true" evaluates to null.

    Update:
    Ok, just to make it complete I want to add the rest here too which turns out quite fun in relation to the above.

    "null Or false" evaluates to null, "null And false" evaluates to false. :)

    The logic is of course still as self-evident as before.

提交回复
热议问题