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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Will this still use indexes efficiently? I think using OR field IS NULL would at least use an index, if this one can't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.