This is a short tip describing the sql coalesce function.
Description
COALESCE accepts a comma separated list of parameters and returns
the first value that is not null in that list or null if all the arguments are null.
Thus
- COALESCE (a1, a2, a3, ..., an)
will return a1 if a1 is not null, a2 if a1 is null but a2 is not null,
a3 if a1, a2 are null but a3 is not null and so on.
The same thing can be achieved by using a CASE. For the snippet above the CASE would be
- CASE WHEN (a1 IS NOT NULL) THEN a1
-
WHEN (a2 IS NOT NULL) THEN a2
-
WHEN (a3 IS NOT NULL) THEN a3
-
...
-
-
WHEN (an IS NOT NULL) THEN an
-
ELSE NULL
Notice that the ELSE NULL at the end ensures that NULL is returned
when all the arguments are null to conform to the coalesce behaviour.
Clearly the coalesce version is much more compact.
Common uses Preferential selection - Usually used when many columns can be used to represent a value but only one should be used at a time.
In this case the parameters are normally specified starting with the most specific or detailed representation. - SELECT COALESCE (name, description) as Product FROM Products
will show the description only if the name is null.
Optional parameters - Coalesce can also be used to provide a way of passing optional parameters.
Normally for a parameter say $P you would do - SELECT * FROM Products WHERE (name = '$P' OR $P IS NULL)
If the parameter $P is passed as NULL all the products will be selected otherwise only
the product with name $P is selected. With coalesce, this can be done as: - SELECT * FROM Products WHERE (name LIKE COALESCE($P, '%' ))
Portability
This function is an ANSI standard function and so is available in most
RDBMs and generally more advisable to use than RDMS specific
functions (e.g SQL Server's ISNULL) .
Hope this was useful.