The MySQL IFNULL is used to replace the NULLs with custom values or custom text. This operator is very useful for replacing annoying NULLS with custom information. The basic syntax behind this IFNULL is as follows:
SELECT IFNULL(expression1, expression2)
This IFNULL operator accepts two arguments. If the first value (expression 1) is not, then it returns the first value. If the expression1 value is NULL, then expression2 is returned.
MySQL IFNULL Operator Example
In this example query, we show you the simple IFNULL operator examples. Here, the first statement returns 10 because 10 is Not Null. The second statement returns 5 because the first argument is Null. Within the last statement, 1/0 is a NULL, so 5 and Wrong returned.
SELECT IFNULL(10, 5);
SELECT IFNULL(NULL, 5);
SELECT IFNULL(1/0, 5), IFNULL(1/0, 'Wrong');
IFNULL Example 2
We are using this Employee Details table for the IFNULL operator demonstration. The below screenshot shows you the data inside this MySQL table
In this example query, we used the IFNULL operator on Middle Name. If the Middle name is Null, then it replaces with ‘No Middle Name’ as Name1, and ‘Tutorial Gateway’ as Name2. Otherwise, it returns the Middle Name.
SELECT CustomerKey, FirstName, IFNULL(MiddleName, 'No Middle Name') AS Name1, IFNULL(MiddleName, 'Tutorial gateway') AS Name2, LastName, YearlyIncome, Phone, Office, Mobile FROM EmployeeDetails;
This time, we are using this MySQL IFNULL on Middle Name, Phone, Office, and Middle columns. If there are any Null values in the phone numbers, then replace them with 0.
SELECT CustomerKey, FirstName, IFNULL(MiddleName, 'Tutorial gateway') AS MName, LastName, YearlyIncome, IFNULL(Phone, 0), IFNULL(Office, 0), IFNULL(Mobile, 0) FROM EmployeeDetails;
Until now, we are using this to replace the column NULL values with custom text. However, you can also use another column value as the replacement value. In this example, (Phone, Office) means, if there are any nulls in the Phone column, then they will be replaced by the corresponding office numbers.
SELECT CustomerKey, FirstName, IFNULL(MiddleName, 'Tutorial gateway') AS MName, LastName, YearlyIncome, IFNULL(Phone, Office), IFNULL(Office, Phone), IFNULL(Mobile, Phone) FROM EmployeeDetails;