简体   繁体   中英

When or why is equals not the opposite of not equals in a SQL query?

In a table containing five records where the Toppings value is "Chocolate", two of them have the value "Yes" in the MaraschinoCherry column, the other three contain nothing in that column (not "No" - nothing/blank).

This query works fine:

select definition from desserts 
where (Toppings = 'Chocolate') and 
      (MaraschinoCherry <> 'Yes') 
order by id

...returning the expected three records; but this one returns nothing at all, rather than the two records I expect:

select definition from desserts 
where (Toppings = 'Chocolate') and 
      (MaraschinoCherry = 'Yes') 
order by id

???

The answer to your question is simple. Any comparison to a NULL value, with two exceptions, produces NULL as the result. So,

MaraschinoCherry = 'Yes'

and

MaraschinoCherry <> 'Yes'

Both return NULL when MaraschinoCherry has a NULL value. NULL comparisons are treated the same as FALSE.

The two exceptions are: IS NULL and IS NOT NULL. Note that "= NULL" always returns NULL, which is interpreted as FALSE.

The normal way to fix this is by using COALESCE:

COALESCE(MaraschinoCherry, 'NO') = 'Yes'

(The function ISNULL() is kind of equivalent, but COALESCE allows more arguments and is standard SQL.)

There are other ways you can fix this, such as by specifying a default value for the column when you define the table, by adding an explicit comparison to NULL, by declaring the column to be "NOT NULL", or in some databases by overriding the behavior of NULLs in comparisons to violate the SQL standards (HIGHLY NOT RECOMMENDED!).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM