Tutorials References Menu

MySQL Tutorial

MySQL HOME MySQL Intro MySQL RDBMS

MySQL SQL

MySQL SQL MySQL SELECT MySQL WHERE MySQL AND, OR, NOT MySQL ORDER BY MySQL INSERT INTO MySQL NULL Values MySQL UPDATE MySQL DELETE MySQL LIMIT MySQL MIN and MAX MySQL COUNT, AVG, SUM MySQL LIKE MySQL Wildcards MySQL IN MySQL BETWEEN MySQL Aliases MySQL Joins MySQL INNER JOIN MySQL LEFT JOIN MySQL RIGHT JOIN MySQL CROSS JOIN MySQL Self Join MySQL UNION MySQL GROUP BY MySQL HAVING MySQL EXISTS MySQL ANY, ALL MySQL INSERT SELECT MySQL CASE MySQL Null Functions MySQL Comments MySQL Operators

MySQL Database

MySQL Create DB MySQL Drop DB MySQL Create Table MySQL Drop Table MySQL Alter Table MySQL Constraints MySQL Not Null MySQL Unique MySQL Primary Key MySQL Foreign Key MySQL Check MySQL Default MySQL Create Index MySQL Auto Increment MySQL Dates MySQL Views

MySQL References

MySQL Data Types MySQL Functions

MySQL Examples

MySQL Examples

MySQL NULL Functions


MySQL IFNULL() and COALESCE() Functions

Look at the following "Products" table:

P_Id ProductName UnitPrice UnitsInStock UnitsOnOrder
1 Jarlsberg 10.45 16 15
2 Mascarpone 32.56 23  
3 Gorgonzola 15.67 9 20

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;