loading

MySQL NULL Functions

MySQL IFNULL() and COALESCE() Functions

Look at the following “Products” table:

P_IdProductNameUnitPriceUnitsInStockUnitsOnOrder
1Jarlsberg10.451615
2Mascarpone32.5623 
3Gorgonzola15.67920

Assume that NULL values may be present in the optional “UnitsOnOrder” column.

Examine the SELECT statement that follows:

				
					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

If an expression is NULL, you can return a different result using the MySQL IFNULL() method.

If the value is NULL, the example below returns 0.

				
					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;
				
			
Share this Doc

MySQL NULL Functions

Or copy link

Explore Topic