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
See also
Examples
Successful casts
FeatureQL
SELECT
f1 := TRY_CAST('123' AS BIGINT), -- Valid string to integer
f2 := TRY_CAST(42 AS DOUBLE), -- Integer to double
f3 := TRY_CAST('2024-01-15' AS DATE) -- Valid string to date
;Result
| f1 BIGINT | f2 VARCHAR | f3 TIMESTAMP |
|---|---|---|
| 123 | 42.0 | 2024-01-15 |
Invalid input → NULL
FeatureQL
SELECT
f1 := TRY_CAST('abc' AS BIGINT), -- Invalid string returns NULL
f2 := TRY_CAST('not-a-date' AS DATE) -- Invalid date string returns NULL
;Result
| f1 BIGINT | f2 TIMESTAMP |
|---|---|
| NULL | NULL |