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>
Alagappan Ramu
  • 2,270
  • 7
  • 27
  • 37

4 Answers4

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
John Woo
  • 258,903
  • 69
  • 498
  • 492
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

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
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.

Walter Mitty
  • 18,205
  • 2
  • 28
  • 58
0

Actually NULL means “a missing unknown value”

Check this page

Vijaychandar
  • 716
  • 5
  • 21