Home >Database >Mysql Tutorial >Why Do '!=' and '<>' Operators Fail to Compare with NULL in SQL?
" Operators Fail to Compare with NULL in SQL? " />
Understanding NULL Comparisons in SQL
SQL uses "!=" and "<>" for inequality checks. However, these operators behave unexpectedly with NULL
values.
The Issue:
Consider these SQL queries:
<code class="language-sql">SELECT * FROM MyTable WHERE MyColumn != NULL; SELECT * FROM MyTable WHERE MyColumn <> NULL; SELECT * FROM MyTable WHERE MyColumn IS NOT NULL;</code>
The first two queries return empty result sets, whereas the third correctly returns 568 rows. Why this discrepancy?
Explanation:
"!=" and "<>" compare values. NULL
, however, isn't a value; it signifies the absence of a value. Therefore, these operators are unsuitable for NULL
comparisons.
Use IS NULL
or IS NOT NULL
instead. These predicates specifically check for the presence or absence of a value. The third query's success stems from its correct use of IS NOT NULL
.
Key Points:
NULL
values, use IS NOT NULL
.NULL
values.NULL
cannot be considered equal to or unequal to any value, as it represents missing data.The above is the detailed content of Why Do '!=' and '<>' Operators Fail to Compare with NULL in SQL?. For more information, please follow other related articles on the PHP Chinese website!