The COALESCE function takes any number of arguments and returns the first one that is not null. However, if all arguments are null then the function itself returns null. It is often used when working with a table that contains null values and we are attempting to substitute with something else.


Basic Syntax

SELECT COALESCE (1,2) -- returns 1
SELECT COALESCE (NULL, 2, 3) -- returns 2

Example 1

Suppose we have the following table:

ITEMPRICEDISCOUNT
A10020
B300null
C20010
The data shows the price of each item in dollars, and the discounted amount in dollars. Suppose, then, that we want to see a table with final prices (that is to say, the price of an item minus the discount). In this scenario, we can try a SQL query that simply does something like select (price - discount) from table.

The issue is that that query will result in a null value for item B, since null cannot be subtracted from zero. The solution is to use COALESCE to substitute null for a 0:

SELECT item, (price - COALESCE(discount,0)) AS final
FROM table

Example 3