Negating a Condition on a Column That Contains NULL Values
Problem
You’re trying to negate a
condition that involves NULL
, but
it’s not working.
Solution
NULL
is special in negations, just like it is
otherwise. Perhaps even more so.
Discussion
Recipe 3.10 pointed out that you can reverse query
conditions, either by changing comparison operators and Boolean
operators, or by using NOT
. These techniques may
not work if a column can contain NULL
. Recall that
the taxpayer
table from Recipe 3.12 looks like this:
+---------+--------+ | name | id | +---------+--------+ | bernina | 198-48 | | bertha | NULL | | ben | NULL | | bill | 475-83 | +---------+--------+
Now suppose you have a query that finds records with taxpayer ID values that are lexically less than 200-00:
mysql> SELECT * FROM taxpayer WHERE id < '200-00';
+---------+--------+
| name | id |
+---------+--------+
| bernina | 198-48 |
+---------+--------+
Reversing this condition by using >=
rather
than <
may not give you the results you want.
It depends on what information you want to obtain. If you want to
select only records with non-NULL
ID values,
>=
is indeed the proper test:
mysql> SELECT * FROM taxpayer WHERE id >= '200-00';
+------+--------+
| name | id |
+------+--------+
| bill | 475-83 |
+------+--------+
But if you want all the records not selected by the original query,
simply reversing the operator will not work. NULL
values fail comparisons both with <
and with
>=
, so you must add an additional clause specifically for ...
Get MySQL Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.