Use TO_DATE(), TRY_TO_DATE(), or CAST to reliably turn VARCHAR values into DATEs in Snowflake.
Snowflake offers three main options: TO_DATE(string [, format])
, TRY_TO_DATE(string [, format])
, and CAST(string AS DATE)
. TO_DATE
errors when the input does not match the expected format, while TRY_TO_DATE
returns NULL
, making it safer for messy data.
Pass the format as the second argument. Example: TO_DATE('31/12/2023','DD/MM/YYYY')
. Snowflake supports Oracle-style date masks, including YYYY
, MM
, DD
, HH24
, and more.
Yes.Wrap the column in the chosen function. When cleaning an events table you might write: SELECT id, TO_DATE(event_ts,'YYYY-MM-DD') AS event_date FROM raw_events;
.
Use TRY_TO_DATE
so malformed rows evaluate to NULL
instead of aborting the query. Afterwards, filter or fix the NULL
rows.
Convert strings to TIMESTAMP_NTZ
first if they contain time-zone info, then cast to DATE.Example: TO_DATE(TO_TIMESTAMP_NTZ('2023-12-31T22:00:00Z'))
.
.
Both compile to the same internal function. Use whichever reads better; performance is identical.
No. Apply separate TRY_TO_DATE calls with different masks or standardize the data upstream.
TO_DATE ignores hours and minutes. Preserve time by converting to TIMESTAMP first.