TRY_CAST
All functions > CORE > TRY_CAST
Returns the given expression casted to the given type, or NULL if the cast fails.
Signatures
Returns: The expression converted to the specified type, or NULL if conversion fails
TRY_CAST(expr: T, as_type: DataTypeEnum.TYPE) → U sql
| Parameter | Type | Required | Description |
|---|---|---|---|
expr | T | Yes | The expression to convert |
as_type | DataTypeEnum.TYPE | Yes | The target data type |
Notes
- Converts a value from one data type to another
- Returns NULL instead of raising an error when the conversion fails
- Supports the same conversions as CAST
- Safe alternative to CAST when the input may contain invalid values
- NULL values remain NULL after casting
Examples
FeatureQL
SELECT
f1 := TRY_CAST('123' AS BIGINT), -- Valid string to integer
f2 := TRY_CAST('abc' AS BIGINT), -- Invalid string returns NULL
f3 := TRY_CAST(42 AS DOUBLE), -- Integer to double
f4 := TRY_CAST('2024-01-15' AS DATE), -- Valid string to date
f5 := TRY_CAST('not-a-date' AS DATE) -- Invalid date string returns NULL
;Result
| f1 BIGINT | f2 BIGINT | f3 VARCHAR | f4 TIMESTAMP | f5 TIMESTAMP |
|---|---|---|---|---|
| 123 | NULL | 42.0 | 2024-01-15 | NULL |
On this page