Skip to main content

TRY_CAST function

Attempts to convert a value from one data type to another. Unlike CAST, if the conversion fails, TRY_CAST returns NULL instead of raising an error.

Syntax

TRY_CAST(expression AS data_type)

Arguments

  • expression: The value or expression to convert.

  • data_type: The target data type to convert to.

Returns

  • The value of expression converted to the specified data_type if the conversion succeeds.

  • NULL if the conversion fails.

Supported Conversions

TRY_CAST supports the same conversions as CAST. See CAST Operator for the complete table.

Examples

-- Example 1: Successful cast
> SELECT TRY_CAST(int64_val AS DOUBLE) FROM TableAllTypes;
-2
2

-- Example 2: Failed cast returns NULL (instead of error)
> SELECT TRY_CAST(str_val AS BIGINT) FROM TableAllTypes;
-- Returns 1 for '1', NULL for 'A'
1
NULL

-- Example 3: Compare with regular CAST
> SELECT CAST('abc' AS BIGINT);
ERROR: invalid input syntax for type bigint

> SELECT TRY_CAST('abc' AS BIGINT);
NULL

See Also

  • CAST function - Standard type conversion (raises error on failure)

  • CAST Operator - Detailed conversion table

  • COALESCE function - Provide default values for NULL