Home > Database > Mysql Tutorial > How to Correctly Select Rows with NULL Values in MySQL?

How to Correctly Select Rows with NULL Values in MySQL?

DDD
Release: 2024-11-30 10:20:21
Original
917 people have browsed it

How to Correctly Select Rows with NULL Values in MySQL?

MySQL: Selecting Rows with NULL Values

While attempting to retrieve rows where a particular column contains a NULL value, the user encounters an empty result set. This discrepancy arises despite the table displaying NULL values when viewed in phpMyAdmin.

The query in question resembles the following:

SELECT pid FROM planets WHERE userid = NULL
Copy after login

After exploring various suggestions, including checking for "NULL" or "null" strings and searching for empty spaces, the user remains unable to retrieve the desired rows. Suspecting that the MyISAM storage engine may be a contributing factor, the user converts the table to InnoDB. However, the issue persists.

Resolving the Issue

The solution lies in understanding the special nature of SQL NULL values. Unlike traditional values, NULLs cannot be equated using the equal sign (=). To correctly retrieve rows with NULL values, the following syntax must be used:

WHERE field IS NULL
Copy after login

This distinction stems from the fact that NULL represents an unknown or undefined value, making it impossible to determine whether it is truly equal to anything, including itself. This principle is enshrined in Codd's Rule 3.

By adjusting the query to:

SELECT pid FROM planets WHERE userid IS NULL
Copy after login

the user should now be able to successfully retrieve the rows with NULL values.

The above is the detailed content of How to Correctly Select Rows with NULL Values in MySQL?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template