The COALESCE
function
The COALESCE
function in Firebird 1.5 and higher can convert NULL
to most anything else.This enables you to perform an on-the-fly conversion and use the result in your further processing, without the need for “if (MyExpression is null) then
” or similar constructions.The function signature is:
COALESCE( Expr1, Expr2, Expr3, … )
COALESCE
returns the value of the first non-NULL
expression in the argument list.If all the expressions are NULL
, it returns NULL
.
This is how you would use COALESCE
to construct a person’s full name from the first, middle and last names, assuming that some middle name fields may be NULL
:
select FirstName
|| coalesce( ' ' || MiddleName, '' )
|| ' ' || LastName
from Persons
Or, to create an as-informal-as-possible name from a table that also includes nicknames, and assuming that both nickname and first name may be NULL
:
select coalesce ( Nickname, FirstName, 'Mr./Mrs.' )
|| ' ' || LastName
from OtherPersons
COALESCE
will only help you out in situations where NULL
can be treated in the same way as some allowed value for the datatype.If NULL
needs special handling, different from any other value, your only option is to use an IF
or CASE
construct after all.