0

i've noticed that this statement for example

SELECT * FROM mammals where animals <> "Dog"

Filters out all the rows that contains Dog on the column animals but ALSO filters out all the rows where animals is null.

Is that normal?

Sebas
  • 21,192
  • 9
  • 55
  • 109
BlueStarry
  • 677
  • 1
  • 7
  • 13

1 Answers1

2

Yes it is.

You have to be null-safe when using nullable columns:

SELECT * FROM `mammals` WHERE COALESCE(`animals`, '-1') <> 'Dog'

Coalesce: https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce

If you were to use an equality comparison instead, there's a nullsafe operator for this:

SELECT * FROM `mammals` WHERE COALESCE(`animals`, '-1') <=> 'Dog'

https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_equal-to

Related SO resource: MySQL comparison with null value

Note: ISNULL (https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_isnull) is another function similar to COALESCE. But the difference is that ISNULL is not ANSI standard and therefore should be avoided whenever possible.

Community
  • 1
  • 1
Sebas
  • 21,192
  • 9
  • 55
  • 109
  • 1
    Will this still use indexes efficiently? I think using `OR field IS NULL` would at least use an index, if this one can't. – Sami Kuhmonen Jul 23 '15 at 17:44