Null Values and Comparisons Involving NULL

Null Values and Comparisons Involving NULL

SQL allows attributes to have a special value NULL, which is called the null value. There are many different interpretations that can be put on null values. Here are some of the most common:

1. Value unknown: that is, "I know there is some value that belongs here but I donít know what it is." An unknown birthdate is an example.

2. Value inapplicable: "There is no value that makes sense here." For instance, if we had a spouse attribute for the MovieStar relation, then an unmarried star might have NULL for that attribute, not because we donít know the spouse's name, but because there is none.

3. Value withheld: "We are not entitled to know the value that belongs here." For instance, an unlisted phone number might appear as NULL in the component for a phone attribute.

We saw in "Outerjoins" how the use of an outerjoin operator produces null values in some components of tuples; SQL allows outerjoins and also produces NULLís when a query involves outerjoins; see "Outerjoins". There are other ways SQL produces NULLís as well. For instance, certain insertions of tuples create null values, as we shall see in "Database Modifications".

In WHERE clauses, we must be prepared for the possibility that a component of some tuple we are examining will be NULL.   There are two important rules to remember when we operate upon a NULL value.

1. When we operate on a NULL and any value, including another NULL, using an arithmetic operator like x or +, the result is NULL.

2. When we compare a NULL value and any value, including another NULL, using a comparison operator like = or >, the result is UNKNOWN. The value UNKNOWN is another truth-value, like TRUE and FALSE; we shall discuss how to manipulate truth-value UNKNOWN shortly.

However, we must remember that, although NULL is a value that can appear in tuples, it is not a constant. Thus, while the above rules apply when we try to operator on an expression whose value is NULL, we cannot use NULL explicitly as an operand.

Example 1: Let x have the value NULL. Then the value of x + 3 is also NULL. However, NULL + 3 is not a legal SQL expression. Similarly, the value of x = 3 is UNKNOWN, because we cannot tell if the value of x, which is NULL, equals the value 3. However, the comparison NULL =  3 is not correct SQL.

Incidentally; the correct way to ask if x has the value NULL is with the expression x IS NULL. This expression has the value TRUE if x has the value NULL and it has value FALSE otherwise. Similarly, x IS NOT NULL has the value TRUE unless the value of x is NULL.

Tags