سؤال

I recently realized that we need to use a special syntax IS NULL to compare a literal to NULL.

Why does = NULL not work here?

هل كانت مفيدة؟

المحلول

Take a look at PSOUG's notes on NULL. As Fabricio Araujo hinted, NULL is not really a value like the number 4 or string 'bacon strips'. In fact, NULL is untyped in the SQL language, which is why you cannot validly use it in an equality comparison. You need the special IS [NOT] NULL syntax to check if a value is NULL or not.

نصائح أخرى

In SQL Server, we have an connection setting to get =NULL to behave equally to IS NULL. But in latest versions is not recommended anymore - it's even marked as deprecated.

The recommended is the SQL Standard way - the IS [NOT] NULL operator.

(And I will not start an war whether 'NULL is a value or a status' here)... hehehe

Rather than justify the is null syntax I think it is better to point out that there are no good general rules-of-thumb when dealing with nulls and the syntax used to handle them. For example:

  1. updating a value uses syntax like set val = null rather than something like set val to null which might mirror the is null syntax better
  2. it is almost always a mistake when dealing with null to say: "nulls behave like so-and-so here, so they should behave like such-and-such here

Here is an excellent essay on the subject from a postgres perspective. Briefly summed up by saying nulls are treated differently depending on the context and don't make the mistake of making any assumptions about them.

Oracle treats NULL as an unknown value. Ask yourself if this equality works.

(unknown amount in George's wallet) = (unknown amount in Harry's wallet)

or otherwise stated

NULL = NULL

The answer is clearly maybe, which is neither true nor false.

EDIT: In response to the comments I will add a little clarification to NULL as I have seen it used.

While NULL really means "not set", in the context of this question I believe the above statement is correct.

There are a number of reasons for a column to have a NULL value:

  • The column is not appropriate to the sub-type or state of the row. (It is known we shouldn't have a value. In this case we shouldn't be comparing the value of the column to another value. Testing for IS NULL may be useful.)
  • The value is not available, or hasn't been recorded in the column. (The value exists but for some reason isn't known by the database. In these cases NULL is equivalent to unknown by the database.)

In some contexts, NULL may be handled in ways that might be considered incorrect, including:

  • NULL values may be replaced with a default value. An unset NOT NULL number is likely to have the value 0. (This does not necessarily mean the value is known to be 0.)
  • An empty string may be converted to NULL or vice versa. (The value may be known, an empty.)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى dba.stackexchange
scroll top