0

I have a table with the following possible values for the column field_value.

But when I try to select all values which are not 'CB', the query result also ignores all NULL values.

Why does this happen?

mysql> select distinct field_value from TableName;
+--------------+
| field_value  |
+--------------+
| S            |
| NULL         |
| CA           |
| CB           |
+--------------+
4 rows in set (6.32 sec)

mysql> select distinct field_value from TableName where field_value!='CB';
+--------------+
| field_value  |
+--------------+
| S            |
| CA           |
+--------------+
2 rows in set (0.15 sec)

mysql>
2
  • you can not compare a field value to NULL with comparison operator , instead you have to use IS NULL operator. Commented Oct 19, 2012 at 3:18
  • stackoverflow.com/search?q=mysql+null Commented Oct 19, 2012 at 3:20

4 Answers 4

2

That's because any comparisons with NULL also yield NULL (i.e. not truthy nor falsy).

The special operators IS NULL and IS NOT NULL are used to make useful comparisons against NULL.

Your query should therefore be:

... WHERE field_value!='CB' OR field_value IS NULL;

See also: Working with NULL values

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

Comments

2

Because NULL is unknown and unknown doesn't mean that is it not equal to CB.

if you want to return null values add a condition (IS NULL) in your query,

SELECT ...
FROM   ...
where field_value != 'CB' OR field_value IS NULL

Comments

1

NULL is not equal to any value. NULL is not unequal to any value. NULL is not even equal to NULL. Try it if you don't believe it.

select * from anytable
where NULL = NULL
or not NULL = NULL
or NULL != NULL
or not NULL != NULL

You should get zero rows retrieved. The result of all four conditions is UNKNOWN. unknown is not the same thing as TRUE. unknown is not the same thing as FALSE. If this sounds like a mess to you, then you are probably starting to understand.

It's best to avoid using nullable columns in WHERE conditions, unless you are prepared to think things through very carefully.

Comments

0

Actually NULL means “a missing unknown value”

Check this page

Comments

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.