How to Use the MySQL IFNULL() Function
In this tutorial, we'll learn how to use the MySQL IFNULL() function. IFNULL() is a function to return the specified value when the expression in NULL. But if the expression is not NULL, it returns the expression.
The syntax of the IFNULL() function is as follow:
IFNULL (expression_1, expression_2)
Let's look at the statement below:
SELECT IFNULL ("Hello!", "NULL") AS Message;
As you can see, IFNULL checks if Hello! is NULL. If Hello! is NULL, it returns NULL, otherwise returns Hello!. Since the string Hello! is not NULL, IFNULL returns Hello!;
The following statement returns 1000 because the first expression is NULL.
SELECT IFNULL (NULL, 1000) AS Message;
For example, we have the following customers table. This table consists of 3 columns, customer_id, customer_name, and group. The group column can be NULL.
SELECT customer_id, customer_name, IFNULL(group, "The customer group is not set!") AS group
As you can see, in this statement, IFNULL() checks the group column if the value is NULL, it returns The customer group is no set!, otherwise returns the value of the group column.
The result set from this statement as follows:
|2||Roland||The customer group is not set!|
As we can see in this result table, in case of the 1st and 3rd customers, since the group is not NULL, IFNULL() returns the value of the group column. But, in case of the 2nd customer, since the group is NULL, IFNULL() returns The customer group is not set!.
In this tutorial, we've learned how to use the MySQL IFNULL() function. IFNULL() is used to return the specified value when the expression is NULL, otherwise returns the expression.