MySQL IFNULL Operator

The MySQL IFNULL is used to replace the NULLs with custom values or custom text. The MySQL IFNULL operator is very useful to replace the annoying NULLS with custom information. The basic syntax behind this MySQL IFNULL is as follows:

SELECT IFNULL(expression1, expression2) 

This IFNULL operator accepts two arguments. If the first value (expression 1) is not null, then it returns the first value. If the expression1 value is NULL, then expression2 is returned

MySQL IFNULL Operator Example 1

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');
MySQL IFNULL Operator 1

MySQL 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

MySQL IFNULL Operator 2

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 `MySQL Tutorial`.EmployeeDetails;
MySQL IFNULL Operator 3

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 `MySQL Tutorial`.EmployeeDetails;
MySQL IFNULL Operator 4

Until now, we are using this IFNULL to replace the column NULL values with custom text. However, you can also use another column value as the replacement value. In this example, IFNULL(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 `MySQL Tutorial`.EmployeeDetails;
MySQL IFNULL Operator 5