i've got a table "bla" like this:
[id] [name] [fk]
1 test 4
2 foo 5
3 bar NULL
if i do the sql query
SELECT * FROM bla WHERE fk <> 4
i only get the record with the id 2. i don't get the record with id 3 where fk is null. I thought NULL != 4. Seems that this is wrong.
Why is this so?
How about
Logic:
NULL
is special in that it represents an "unknown" value. This can't be compared to numbers (or any other value for that matter), hence the result -Is
NULL
<> 4? The answer is - don't know. Is 4 different from an unknown value?Try this instead:
NULL
doesn't compare equal to anything. You'll need to accept nulls explicitly:See Working with NULL for more information about
NULL
handling.Because
NULL
stands forUNKNOWN
, and when you compare a value withUNKNOWN
, the result will always be false.Take a look at this comparisons -
If you want to fetch the records containing
NULL
, you need to re-write your query this way -For more information, see Wikipedia.
NULL is not a value, but rather the unknown absence of a value. If you'd like to test for NULL, you have to do so explicitly by using
IS NULL
andIS NOT NULL
. For example, NULL will test FALSE even against NULL itself. So, working with NULL is only done with the aforementioned functions (andISNULL()
). Your query could be rewritten asFollowing statement should help:
SELECT * FROM bla WHERE COALESCE(fk,0) <> 4