Home > Database > Mysql Tutorial > Why Does 'CODE!='C'' Exclude NULL Values in MySQL Queries?

Why Does 'CODE!='C'' Exclude NULL Values in MySQL Queries?

Susan Sarandon
Release: 2025-01-09 19:37:45
Original
539 people have browsed it

Why Does

Comparison of NULL values ​​in MySQL

In MySQL, comparing columns containing NULL values ​​can present challenges because the behavior is different from standard equality comparisons. This article explores why a query like "SELECT * from TABLE where CODE!='C'" excludes rows with CODE=NULL, even if 'C' is not NULL.

NULL comparison behavior

When comparing a column to a non-NULL value (such as "CODE!='C'"), the query returns rows where CODE matches 'C' and excludes all other values, including NULL. This behavior results from SQL treating NULL as a unique value that does not participate in standard comparisons.

To include NULL values ​​in a comparison, they must be checked explicitly using the IS NULL or IS NOT NULL operator. For example, the following query will return all rows where CODE is NULL or not equal to 'C':

<code class="language-sql">SELECT * from TABLE where CODE IS NULL OR CODE!='C'</code>
Copy after login

Explanation of CODE!='C' behavior

The reason "CODE!='C'" does not return rows with CODE=NULL is that the query will evaluate to false for any comparison involving NULL. Even if 'C' is not NULL, comparing it to a NULL value will always result in false.

Alternative comparison operators

MySQL provides an alternative comparison operator "<=" (less than or equal to) that can be used to compare values ​​that contain NULL. The evaluation of "x <= y" returns true if x is less than, equal to, or NULL, false otherwise.

You can return all rows where CODE is NULL or not equal to 'C' by using "CODE <= 'C' OR CODE IS NULL" instead of "CODE!='C'".

The above is the detailed content of Why Does 'CODE!='C'' Exclude NULL Values in MySQL Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template