How to Use the ISNULL() Function in MySQL

08/04/2021

Contents

In this article, you will learn how to use the ISNULL() function in MySQL.

Using the ISNULL() function in MySQL

The ISNULL() function in MySQL is used to test whether a value is null or not.

Syntax

The syntax for using the ISNULL() function in MySQL is as follows:

SELECT ISNULL(column_name) FROM table_name;

Examples

Suppose we have a table named “employees” with columns “employee_id”, “first_name”, “last_name”, and “salary”. We can use the ISNULL() function to find the employees who do not have a last name as follows:

SELECT employee_id, first_name, last_name FROM employees WHERE ISNULL(last_name);

This query will return the employee ID, first name, and last name of the employees who do not have a last name in the “employees” table.

If we want to find the employees who have a last name, we can use the following query:

SELECT employee_id, first_name, last_name FROM employees WHERE NOT ISNULL(last_name);

This query will return the employee ID, first name, and last name of the employees who have a last name in the “employees” table.

We can also use the ISNULL() function with the IF() function to replace null values with a default value. For example:

SELECT employee_id, first_name, IF(ISNULL(last_name), 'Unknown', last_name) AS last_name, salary FROM employees;

This query will return the employee ID, first name, last name (replaced with “Unknown” if null), and salary of all employees in the “employees” table.