try_cast function
Applies to: Databricks SQL
Databricks Runtime 10.4 LTS and above
Returns the value of sourceExpr cast to the targetType if the cast is supported; otherwise, it returns NULL, provided that the cast from the type of sourceExpr to targetType is supported. If the source and target types are not a valid cast combination, a DATATYPE_MISMATCH error is returned. See Returns for supported cast combinations.
Syntax
try_cast(sourceExpr AS targetType)
Arguments
sourceExpr: Any castable expression.targetType: The type of the result.
Returns
The result is of type targetType.
This function is a more relaxed variant of cast function which includes a detailed description.
try_cast differs from cast function by tolerating the following conditions as long as the cast from the type of expr to type is supported:
- If a
sourceExprvalue cannot fit within the domain oftargetTypethe result isNULLinstead of an overflow error. - If a
sourceExprvalue is not well formed or contains invalid characters the result isNULLinstead of an invalid data error.
Exception to the above are:
Examples
SQL
> SELECT try_cast('10' AS INT);
10
> SELECT try_cast('a' AS INT);
NULL