MySQL NULL Functions

Bhavitha Cherukuri
2 min readAug 1, 2023

--

NULL functions are provided to perform operations on NULL values that are stored in our database tables.

A NULL value is like a placeholder in the database when we have data that is missing or the required data is not available. It is a flexible value that is not part of any practical data type and can be put in the column of any data type, like string, int, varchar etc.

Following are the various features of a NULL value −

  • The NULL value is different from a zero value or a field that contains a space. A record with a NULL value is one that has been left blank during record creation.
  • The NULL value assists us in removing ambiguity from data. Also, a NULL value is beneficial to maintain the uniform datatype across the column.

If a user entered their DOB in the column of their mobile number, ambiguity could arise when contact was required. To overcome this, we have to check the data before insertion and update any data that is not of the date datatype with a NULL function.

MySQL IFNULL() and COALESCE() Functions

Look at the following “Products” table:

Products

Suppose that the “UnitsOnOrder” column is optional, and may contain NULL values.

Look at the following SELECT statement:

SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)
FROM Products;

In the example above, if any of the “UnitsOnOrder” values are NULL, the result will be NULL.

MySQL IFNULL() Function

The MySQL IFNULL() function lets you return an alternative value if an expression is NULL.

The example below returns 0 if the value is NULL:

SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))
FROM Products;

MySQL COALESCE() Function

Or we can use the COALESCE() function, like this:

SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))
FROM Products;

--

--

Bhavitha Cherukuri

My passion for writing motivated me to start writing blogs and the content within is written in a simple and easy format. so that readers can understand easily.