MySQL NULL Value Handling

We already know that MySQL usesSELECTcommand andWHEREclause to read data in the data table, but when the provided query condition field is NULL, the command may not work properly.

In MySQL, NULL is used to represent missing or unknown data. Handling NULL values requires special care because in the database it may cause results different from what you expect.

To handle this situation, MySQL provides three main operators:

  • IS NULL:When the column value is NULL, this operator returns true.
  • IS NOT NULL:When the column value is not NULL, the operator returns true.
  • <=>:Comparison operator (unlike the = operator), which returns true when the two compared values are equal or when both are NULL.

The conditional comparison operation for NULL is special. You cannot use = NULL or != NULL to find NULL values in a column.

In MySQL, comparing NULL with any other value (even NULL) always returns NULL, that is, NULL = NULL returns NULL.

In MySQL, use the IS NULL and IS NOT NULL operators to handle NULL.

Note:

select * , columnName1+ifnull(columnName2,0) from tableName;

columnName1 and columnName2 are of type int. When columnName2 has a NULL value, columnName1 + columnName2 = NULL. ifnull(columnName2,0) converts the NULL value in columnName2 to 0.

Common considerations and tips for handling NULL values in MySQL

1. Check whether it is NULL:

To check whether a column is NULL, you can use the IS NULL or IS NOT NULL conditions.

SELECT * FROM employees WHERE department_id IS NULL;
SELECT * FROM employees WHERE department_id IS NOT NULL;

2. Use the COALESCE function to handle NULL:

The COALESCE function can be used to replace NULL values. It accepts multiple arguments and returns the first non-NULL value in the argument list:

SELECT product_name, COALESCE(stock_quantity, 0) AS actual_quantity
FROM products;

In the above SQL statement, if the stock_quantity column is NULL, COALESCE will return 0.

3. Use the IFNULL function to handle NULL:

The IFNULL function is MySQL's specific version of COALESCE. It accepts two arguments; if the first argument is NULL, it returns the second argument.

SELECT product_name, IFNULL(stock_quantity, 0) AS actual_quantity
FROM products;

4. NULL sorting:

When sorting with the ORDER BY clause, NULL values are placed at the end of the sort by default. If you want to place NULL values first, use ORDER BY column_name ASC NULLS FIRST; conversely, use ORDER BY column_name DESC NULLS LAST.

SELECT product_name, price
FROM products
ORDER BY price ASC NULLS FIRST;

5. Use the <=> operator for NULL comparison:

The <=> operator is a special operator in MySQL used to compare whether two expressions are equal. It also returns TRUE for comparisons involving NULL values. It can be used for equality comparisons with NULL values.

SELECT * FROM employees WHERE commission <=> NULL;

6. Note how aggregate functions handle NULL:

When using aggregate functions (such as COUNT, SUM, AVG), they ignore NULL values, which may lead to unexpected results. If you want to treat NULL as 0, you can use COALESCE or IFNULL.

SELECT AVG(COALESCE(salary, 0)) AS avg_salary FROM employees;

This way, even if salary is NULL, the aggregate function will treat it as 0.

When handling NULL values, be particularly careful to ensure that the semantics of queries and operations match expectations. When designing table structures, you also need to consider the usage scenarios and appropriateness of NULL values.


Using NULL values in the command prompt

In the following example, assume that the table example_test_tbl in the database EXAMPLE has two columns, example_author and example_count, and NULL values are inserted into example_count.

Example

Try the following example:

Create data table example_test_tbl

root@host# mysql -u root -p password; Enter password:******* mysql> use EXAMPLE; Database changed mysql> create table example_test_tbl -> ( -> example_author varchar(40) NOT NULL, -> example_count INT -> ); Query OK, 0 rows affected (0.05 sec) mysql> INSERT INTO example_test_tbl (example_author, example_count) values ('EXAMPLE', 20); mysql> INSERT INTO example_test_tbl (example_author, example_count) values ('Example Tutorial', NULL); mysql> INSERT INTO example_test_tbl (example_author, example_count) values ('Google', NULL); mysql> INSERT INTO example_test_tbl (example_author, example_count) values ('FK', 20); mysql> SELECT * from example_test_tbl; +---------------+--------------+ | example_author | example_count | +---------------+--------------+ | EXAMPLE | 20| | Example Tutorial |NULL | | Google | NULL | | FK | 20 | +---------------+--------------+ 4 rows in set (0.01 sec)

In the following example you can see that the = and != operators are not effective:

mysql> SELECT * FROM example_test_tbl WHERE example_count = NULL; Empty set (0.00 sec) mysql> SELECT * FROM example_test_tbl WHERE example_count != NULL; Empty set (0.01 sec)

To find whether the example_test_tbl column in the data table is NULL, you must useIS NULLandIS NOT NULL, as in the following example:

mysql> SELECT * FROM example_test_tbl WHERE example_count IS NULL; +---------------+--------------+ | example_author | example_count| +---------------+--------------+ | Example Tutorial |NULL | | Google | NULL | +---------------+--------------+ 2 rows in set (0.01 sec) mysql> SELECT * from example_test_tbl WHERE example_count IS NOT NULL; +---------------+--------------+ | example_author | example_count | +---------------+--------------+ | EXAMPLE | 20 | | FK | 20 | +---------------+--------------+ 2 rows in set (0.01 sec)

Using PHP scripts to handle NULL values

In PHP scripts, you can use if...else statements to determine whether a variable is empty, and generate corresponding conditional statements.

In the following example, PHP sets the $example_count variable, and then uses that variable to compare with the example_count field in the data table:

MySQL ORDER BY test:

<?php $dbhost = 'localhost'; //MySQL server host address $dbuser = 'root'; //MySQL username $dbpass = '123456'; //MySQL username password $conn = mysqli_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Connection failed:' . mysqli_error($conn)); } //Set the encoding to prevent Chinese garbled text mysqli_query($conn , "set names utf8"); if( isset($example_count )) { $sql = "SELECT example_author, example_count FROM example_test_tbl WHERE example_count = $example_count"; } else { $sql = "SELECT example_author, example_count FROM example_test_tbl WHERE example_count IS NULL"; } mysqli_select_db( $conn, 'EXAMPLE' ); $retval = mysqli_query( $conn, $sql ); if(! $retval ) { die('Unable to read data:' . mysqli_error($conn)); } echo '<h2>Example Tutorial IS NULL Test<h2>'; echo '<table border="1"><tr><td>Author</td><td>Login times</td></tr>'; while($row = mysqli_fetch_array($retval, MYSQL_ASSOC)) { echo "<tr>". "<td>{$row['example_author']} </td> ". "<td>{$row['example_count']} </td> ". "</tr>"; } echo '</table>'; mysqli_close($conn); ?>

The output result is shown in the following figure:

Other extensions