Snowflake CAST and TRY_CAST: Converting Data Types
In Snowflake, the CAST
function and ::
operator convert data from one type to another, ensuring that data fits the required format for operations or consistency in databases. If a conversion is not possible, an error is usually thrown. However, TRY_CAST
provides a safer alternative by returning NULL instead of an error if the conversion fails.
Syntax
CAST
Syntax
::
Operator Syntax
TRY_CAST
Syntax
Parameters
- source_expr: The value or expression you want to convert.
- target_data_type: The data type to which you want the expression converted.
Usage Notes
CAST
and::
will throw an error if the conversion isn’t possible.TRY_CAST
handles potential errors by returningNULL
instead of failing.TRY_CAST
works only for string expressions into specific types like VARCHAR, NUMBER, DATE, BOOLEAN, and TIMESTAMP variations.
Examples
CAST
Input Data
varchar_value | number_value | timestamp_value |
---|---|---|
9.8765 | 1.2345 | 2024-05-09 14:32:29.135 |
Convert a String to a Number with Specified Scale (2)
converted_value |
---|
9.88 |
Using :: for Quick Conversion
converted_value |
---|
9.87650 |
Convert a Number to an Integer
converted_integer |
---|
1 |
TRY_CAST
Safe Conversion with TRY_CAST
safe_date |
---|
2024-01-01 |
safe_date |
---|
NULL |
Date 'not-a-date' is not recognized
Special Conversion Cases
- Handle Invalid Date Formats
- Convert Strings
