Alex Rivera | Logout

why is null not equal to null false

Asked 2009-12-02T16:12:08.987
24

I was reading this article: Get null == null in SQL

And the consensus is that when trying to test equality between two (nullable) sql columns, the right approach is:

where ((A=B) OR (A IS NULL AND B IS NULL))

When A and B are NULL, (A=B) still returns FALSE, since NULL is not equal to NULL. That is why the extra check is required.

What about when testing inequalities? Following from the above discussion, it made me think that to test inequality I would need to do something like:

WHERE ((A <> B) OR (A IS NOT NULL AND B IS NULL) OR (A IS NULL AND B IS NOT NULL))

However, I noticed that that is not necessary (at least not on informix 11.5), and I can just do:

where (A<>B)

If A and B are NULL, this returns FALSE. If NULL is not equal to NULL, then shouldn't this return TRUE?

EDIT
These are all good answers, but I think my question was a little vague. Allow me to rephrase:

Given that either A or B can be NULL, is it enough to check their inequality with

where (A<>B)

Or do I need to explicitly check it like this:

WHERE ((A <> B) OR (A IS NOT NULL AND B IS NULL) OR (A IS NULL AND B IS NOT NULL))

REFER to this thread for the answer to this question.

Edit
Report

2 Answers

38

Because that behavior follows established ternary logic where NULL is considered an unknown value.

If you think of NULL as unknown, it becomes much more intuitive:

Is unknown a equal to unknown b? There's no way to know, so: unknown.

answered 2009-12-02T16:17:25.277
4

The short answer is... NULLs are weird, they don't really behave like you'd expect.

Here's a great paper on how NULLs work in SQL. I think it will help improve your understanding of the topic. I think the sections on handling null values in expressions will be especially useful for you.

http://www.oracle.com/technology/oramag/oracle/05-jul/o45sql.html

answered 2009-12-02T16:14:43.270

Your Answer