Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL values in where clause

Tags:

sql

null

mysql

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?

like image 981
caspermc Avatar asked Jul 26 '11 08:07

caspermc


2 Answers

NULL doesn't compare equal to anything. You'll need to accept nulls explicitly:

where fk <> 4 or fk is null;

See Working with NULL for more information about NULL handling.

like image 62
Mat Avatar answered Sep 17 '22 18:09

Mat


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:

SELECT * FROM bla WHERE fk <> 4 OR FK IS NULL
like image 29
Oded Avatar answered Sep 21 '22 18:09

Oded