CAST / CONVERT / TRY_CAST
Category: Conversion Functions
Platform Support:
✅ Snowflake | ✅ BigQuery | ✅ Databricks
Description
Convert data from one type to another. CAST is standard SQL, CONVERT is platform-specific, and TRY_CAST returns NULL on conversion failure instead of error. Essential for data type transformations, cleaning, and ensuring type compatibility.
Syntax
CAST (Standard SQL):
CAST(expression AS target_type)
-- Or using :: operator (Snowflake, Databricks)
expression::target_typeTRY_CAST (Safe Conversion):
TRY_CAST(expression AS target_type)
-- Returns NULL instead of error on failureCONVERT:
-- Snowflake
TO_NUMBER(expression)
TO_VARCHAR(expression)
TO_DATE(expression)
TO_TIMESTAMP(expression)
-- BigQuery
CAST(expression AS type)
SAFE_CAST(expression AS type) -- Like TRY_CASTPlatform-Specific Notes
Snowflake:
- CAST and :: operator
- TRY_CAST for safe conversion
- TO_* functions (TO_NUMBER, TO_DATE, etc.)
- Extensive format support
BigQuery:
- CAST standard
- SAFE_CAST instead of TRY_CAST
- Format strings in PARSE_DATE, PARSE_TIMESTAMP
- Strict type checking
Databricks:
- CAST and :: operator
- TRY_CAST supported
- Standard Spark SQL conversion functions
- Compatible with Hive types
Example 1: Basic Type Conversions
All Platforms:
SELECT
-- String to number
CAST('123' AS INTEGER) as str_to_int,
CAST('123.45' AS DECIMAL(10,2)) as str_to_decimal,
-- Number to string
CAST(123 AS VARCHAR) as int_to_str,
CAST(123.45 AS VARCHAR) as decimal_to_str,
-- String to date
CAST('2024-01-15' AS DATE) as str_to_date,
-- Date to string
CAST(CURRENT_DATE AS VARCHAR) as date_to_str,
-- Timestamp conversions
CAST('2024-01-15 10:30:00' AS TIMESTAMP) as str_to_timestamp;Result:
str_to_int | str_to_decimal | int_to_str | decimal_to_str | str_to_date | date_to_str | str_to_timestamp |
|---|---|---|---|---|---|---|
123 | 123.45 | "123" | "123.45" | 2024-01-15 | "2024-01-20" | 2024-01-15 10:30:00 |
Example 2: TRY_CAST - Safe Conversion
Snowflake/Databricks:
SELECT
value,
CAST(value AS INTEGER) as cast_result, -- Fails on 'invalid'
TRY_CAST(value AS INTEGER) as try_cast_result -- Returns NULL
FROM (
VALUES ('123'), ('456'), ('invalid'), (NULL)
) AS t(value);BigQuery:
SELECT
value,
CAST(value AS INT64) as cast_result,
SAFE_CAST(value AS INT64) as safe_cast_result
FROM UNNEST(['123', '456', 'invalid', NULL]) AS value;Sample Data:
value |
|---|
123 |
456 |
invalid |
NULL |
Result:
value | cast_result | try_cast_result |
|---|---|---|
123 | 123 | 123 |
456 | 456 | 456 |
invalid | ERROR | NULL |
NULL | NULL | NULL |
Example 3: Data Cleaning with TRY_CAST
All Platforms:
SELECT
customer_id,
phone_raw,
email_raw,
age_raw,
-- Clean and convert
TRY_CAST(phone_raw AS VARCHAR(20)) as phone_clean,
TRY_CAST(age_raw AS INTEGER) as age_clean,
-- Flag invalid data
CASE
WHEN TRY_CAST(age_raw AS INTEGER) IS NULL AND age_raw IS NOT NULL
THEN 'Invalid Age'
ELSE 'Valid'
END as data_quality_flag
FROM customer_import
WHERE TRY_CAST(age_raw AS INTEGER) IS NOT NULL OR age_raw IS NULL;Sample Data (customer_import table):
customer_id | phone_raw | email_raw | age_raw |
|---|---|---|---|
1 | 555-1234 | 35 | |
2 | 555-5678 | forty | |
3 | invalid | 28 | |
4 | 555-9012 | NULL |
Result (filtered for valid ages):
customer_id | phone_raw | age_raw | age_clean | data_quality_flag |
|---|---|---|---|---|
1 | 555-1234 | 35 | 35 | Valid |
3 | invalid | 28 | 28 | Valid |
4 | 555-9012 | NULL | NULL | Valid |
Example 4: Date/Time Conversions
Snowflake:
SELECT
-- String to date with format
TO_DATE('01/15/2024', 'MM/DD/YYYY') as us_date,
TO_DATE('15/01/2024', 'DD/MM/YYYY') as eu_date,
-- String to timestamp
TO_TIMESTAMP('2024-01-15 14:30:00', 'YYYY-MM-DD HH24:MI:SS') as timestamp_val,
-- Unix timestamp to timestamp
TO_TIMESTAMP(1705329000) as from_unix,
-- Extract parts
TO_NUMBER(TO_CHAR(CURRENT_DATE, 'YYYY')) as year_number;BigQuery:
SELECT
-- Parse date with format
PARSE_DATE('%m/%d/%Y', '01/15/2024') as us_date,
PARSE_DATE('%d/%m/%Y', '15/01/2024') as eu_date,
-- Parse timestamp
PARSE_TIMESTAMP('%Y-%m-%d %H:%M:%S', '2024-01-15 14:30:00') as timestamp_val,
-- Unix timestamp
TIMESTAMP_SECONDS(1705329000) as from_unix,
-- Format date
FORMAT_DATE('%Y', CURRENT_DATE()) as year_string;Databricks:
SELECT
-- String to date
TO_DATE('01/15/2024', 'MM/dd/yyyy') as us_date,
TO_DATE('15/01/2024', 'dd/MM/yyyy') as eu_date,
-- String to timestamp
TO_TIMESTAMP('2024-01-15 14:30:00', 'yyyy-MM-dd HH:mm:ss') as timestamp_val,
-- Unix timestamp
FROM_UNIXTIME(1705329000) as from_unix,
-- Extract year
YEAR(CURRENT_DATE()) as year_number;Example 5: Numeric Precision Control
All Platforms:
SELECT
price,
-- Different precision levels
CAST(price AS INTEGER) as as_integer, -- Truncates decimals
CAST(price AS DECIMAL(10,0)) as as_decimal_0,
CAST(price AS DECIMAL(10,2)) as as_decimal_2,
CAST(price AS DECIMAL(10,4)) as as_decimal_4,
-- Rounding with CAST
ROUND(price, 2)::DECIMAL(10,2) as rounded_2
FROM (
SELECT 123.456789 as price
);Result:
price | as_integer | as_decimal_0 | as_decimal_2 | as_decimal_4 | rounded_2 |
|---|---|---|---|---|---|
123.456789 | 123 | 123 | 123.46 | 123.4568 | 123.46 |
Example 6: JSON to Typed Data
Snowflake:
SELECT
json_data,
json_data:customer_id::INTEGER as customer_id,
json_data:name::VARCHAR as name,
json_data:purchase_amount::DECIMAL(10,2) as amount,
TRY_CAST(json_data:is_premium::VARCHAR AS BOOLEAN) as is_premium
FROM orders_json;BigQuery:
SELECT
json_data,
CAST(JSON_VALUE(json_data, '$.customer_id') AS INT64) as customer_id,
JSON_VALUE(json_data, '$.name') as name,
CAST(JSON_VALUE(json_data, '$.purchase_amount') AS NUMERIC) as amount,
SAFE_CAST(JSON_VALUE(json_data, '$.is_premium') AS BOOL) as is_premium
FROM orders_json;Databricks:
SELECT
json_data,
CAST(get_json_object(json_data, '$.customer_id') AS INT) as customer_id,
get_json_object(json_data, '$.name') as name,
CAST(get_json_object(json_data, '$.purchase_amount') AS DECIMAL(10,2)) as amount,
TRY_CAST(get_json_object(json_data, '$.is_premium') AS BOOLEAN) as is_premium
FROM orders_json;Common Data Type Conversions
From Type | To Type | Example |
|---|---|---|
STRING | INTEGER |
|
STRING | DECIMAL |
|
STRING | DATE |
|
STRING | TIMESTAMP |
|
STRING | BOOLEAN |
|
INTEGER | STRING |
|
DECIMAL | INTEGER |
|
DATE | STRING |
|
TIMESTAMP | DATE |
|
BOOLEAN | STRING |
|
CAST vs TRY_CAST Decision
Scenario | Use | Reason |
|---|---|---|
Trusted data | CAST | Fail fast on errors |
User input | TRY_CAST | Handle invalid gracefully |
Data quality checks | TRY_CAST | Identify bad data |
ETL pipeline | TRY_CAST | Prevent pipeline failures |
Known format | CAST | Performance (no error handling) |
Mixed quality | TRY_CAST | Filter out bad records |
Common Conversion Patterns
Clean and filter invalid data:
SELECT *
FROM raw_data
WHERE TRY_CAST(age_column AS INTEGER) IS NOT NULL
AND TRY_CAST(date_column AS DATE) IS NOT NULL;Provide defaults for failed conversions:
SELECT
COALESCE(TRY_CAST(value AS INTEGER), 0) as value_with_default
FROM source_table;Track conversion failures:
SELECT
COUNT(*) as total_records,
COUNT(TRY_CAST(column AS INTEGER)) as valid_conversions,
COUNT(*) - COUNT(TRY_CAST(column AS INTEGER)) as failed_conversions
FROM source_table;Performance Considerations
- CAST is faster than TRY_CAST (no error handling)
- Implicit conversions can slow queries
- Convert once, store properly typed
- Index converted columns if filtered frequently
- Use appropriate precision to save storage
Best Practices
- Use TRY_CAST for untrusted data: Prevent query failures
- Specify precision: Don't rely on defaults
- Validate before converting: Check formats first
- Handle NULLs explicitly: Use COALESCE if needed
- Document format assumptions: Especially for dates
- Test edge cases: Empty strings, special characters
- Use appropriate types: Don't store numbers as strings
- Consider performance: CAST in WHERE can prevent index use
Interested to Learn More? Try Out the Free 14-Days Trial
One AI-native workspace to build, ship, and monitor dbt™ — without the tool sprawl.