coalesce function

Applies to: check marked yes Databricks SQL check marked yes Databricks Runtime

Returns the first non-null argument.

Syntax

coalesce(expr1 [, ...] )

Arguments

Returns

The result type is the least common type of the arguments.

There must be at least one argument. Unlike for regular functions where all arguments are evaluated before invoking the function, coalesce evaluates arguments left to right until a non-null value is found. If all arguments are NULL, the result is NULL.

Special considerations apply to VARIANT types. See isnull function for details.

Examples

> SELECT coalesce(NULL, 1, NULL);
 1

-- The following example raises a runtime error because the second argument is evaluated.
>  SELECT coalesce(NULL, 5 / 0);
 Error: DIVISION_BY_ZERO

-- The following example raises no runtime error because the second argument is not evaluated.
> SELECT coalesce(2, 5 / 0);
 2

> SELECT coalesce(NULL, 'hello');
 hello