// SQL snippet

Safely convert strings to dates in SQL

Dates typed or imported as text range from '2026-03-01' to '3/1/26' to plain nonsense. Convert leniently and keep the rejects visible.

Main statement
SQL Server
Также охватывает
PostgreSQL MySQL

The task

Converting an imported text column to DATE fails the whole statement as soon as one row is malformed. TRY_CAST turns bad values into NULL so the load continues.

The snippet

Written for SQL Server. Versions for PostgreSQL and MySQL are under Variations.

SQL Server
SELECT TRY_CAST(raw_date AS DATE) AS event_date
FROM staging.events;

Как это работает

TRY_CAST applies the server's date-parsing rules and returns NULL for anything unparseable. Pair it with a WHERE TRY_CAST(...) IS NULL query to list rejected rows for fixing. Note the parse depends on the session's language and DATEFORMAT settings for formats like '3/1/26'. On PostgreSQL a regex check is not enough, because '2026-02-30' matches the pattern and still fails the cast; pg_input_is_valid does the real check.

Variations

MySQL: STR_TO_DATE returns NULL (with a warning) on a mismatch

MySQL
SELECT STR_TO_DATE(raw_date, '%Y-%m-%d') AS event_date
FROM staging.events;

PostgreSQL 16+

PostgreSQL
SELECT CASE
           WHEN pg_input_is_valid(raw_date, 'date')
           THEN raw_date::DATE
       END AS event_date
FROM staging.events;

Questions that come up

Why did '3/1/26' convert to a strange date?

Ambiguous orders depend on server settings: SQL Server's default US language parses it as March 1. Use explicit formats (STR_TO_DATE with a mask on MySQL, or the 'yyyy-MM-dd' style with TRY_CONVERT style 23 on SQL Server) so the result cannot depend on configuration.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.