Curriculum
Course: MYSQL
Login

Curriculum

MYSQL

MySQL References

0/140
Text lesson

MySQL NULL Functions

MySQL IFNULL() and COALESCE() Functions

Take a 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

Consider the following SELECT statement, where the “UnitsOnOrder” column is optional and may contain NULL values:

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

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

MySQL IFNULL() Function

The MySQL IFNULL() function allows you to specify an alternative value if an expression is NULL.

The example below returns 0 when the value is NULL:

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

MySQL COALESCE() Function

Alternatively, we can use the COALESCE() function, as shown here:

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