Documentation Home
MySQL Tutorial
Related Documentation Download this Excerpt
PDF (US Ltr) - 199.2Kb
PDF (A4) - 200.1Kb


4.4.6 Working with NULL Values

TheNULL value can be surprising until you get used to it. Conceptually,NULL meansa missing unknown value and it is treated somewhat differently from other values.

To test forNULL, use theIS NULL andIS NOT NULL operators, as shown here:

mysql> SELECT 1 IS NULL, 1 IS NOT NULL;+-----------+---------------+| 1 IS NULL | 1 IS NOT NULL |+-----------+---------------+|         0 |             1 |+-----------+---------------+

You cannot use arithmetic comparison operators such as=,<, or<> to test forNULL. To demonstrate this for yourself, try the following query:

mysql> SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL;+----------+-----------+----------+----------+| 1 = NULL | 1 <> NULL | 1 < NULL | 1 > NULL |+----------+-----------+----------+----------+|     NULL |      NULL |     NULL |     NULL |+----------+-----------+----------+----------+

Because the result of any arithmetic comparison withNULL is alsoNULL, you cannot obtain any meaningful results from such comparisons.

In MySQL,0 orNULL means false and anything else means true. The default truth value from a boolean operation is1.

This special treatment ofNULL is why, in the previous section, it was necessary to determine which animals are no longer alive usingdeath IS NOT NULL instead ofdeath <> NULL.

TwoNULL values are regarded as equal in aGROUP BY.

When doing anORDER BY,NULL values are presented first if you doORDER BY ... ASC and last if you doORDER BY ... DESC.

A common error when working withNULL is to assume that it is not possible to insert a zero or an empty string into a column defined asNOT NULL, but this is not the case. These are in fact values, whereasNULL meansnot having a value. You can test this easily enough by usingIS [NOT] NULL as shown:

mysql> SELECT 0 IS NULL, 0 IS NOT NULL, '' IS NULL, '' IS NOT NULL;+-----------+---------------+------------+----------------+| 0 IS NULL | 0 IS NOT NULL | '' IS NULL | '' IS NOT NULL |+-----------+---------------+------------+----------------+|         0 |             1 |          0 |              1 |+-----------+---------------+------------+----------------+

Thus it is entirely possible to insert a zero or empty string into aNOT NULL column, as these are in factNOT NULL. SeeProblems with NULL Values.