Why does NULL = NULL evaluate to false in SQL server

前端 未结 19 1535
一向
一向 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:45

    The answers here all seem to come from a CS perspective so I want to add one from a developer perspective.

    For a developer NULL is very useful. The answers here say NULL means unknown, and maybe in CS theory that's true, don't remember, it's been a while. In actual development though, at least in my experience, that happens about 1% of the time. The other 99% it is used for cases where the value is not UNKNOWN but it is KNOWN TO BE ABSENT.

    For example:

    • Client.LastPurchase, for a new client. It is not unknown, it is known that he hasn't made a purchase yet.

    • When using an ORM with a Table per Class Hierarchy mapping, some values are just not mapped for certain classes.

    • When mapping a tree structure a root will usually have Parent = NULL

    • And many more...

    I'm sure most developers at some point wrote WHERE value = NULL, didn't get any results, and that's how they learned about IS NULL syntax. Just look how many votes this question and the linked ones have.

    SQL Databases are a tool, and they should be designed the way which is easiest for their users to understand.

提交回复
热议问题