Safely convert strings to numbers in SQL
Import tables type everything as text. Converting a numeric column crashes the moment one row holds junk.
The task
One bad row ('N/A') aborts every CAST(raw_value AS DECIMAL) in the batch. TRY_CAST returns NULL instead of raising an error.
The snippet
Written for SQL Server. Versions for PostgreSQL and MySQL are under Variations.
SELECT TRY_CAST(raw_value AS DECIMAL(12, 2)) AS amount
FROM staging.import_rows;
How it works
TRY_CAST attempts the conversion and yields NULL when the text is not a valid number, so bad rows surface as NULL instead of killing the statement. Filter them out with IS NULL to audit what failed. TRY_CONVERT is the same idea with a style argument. Oracle 12.2+ has the equivalent CAST(raw_value AS NUMBER DEFAULT NULL ON CONVERSION ERROR), plus VALIDATE_CONVERSION to test a value first.
Variations
PostgreSQL
PostgreSQLSELECT CASE
WHEN raw_value ~ '^-?[0-9]+(\.[0-9]+)?$'
THEN raw_value::DECIMAL(12, 2)
END AS amount
FROM staging.import_rows;
MySQL
MySQLSELECT CASE
WHEN raw_value REGEXP '^-?[0-9]+(\\.[0-9]+)?$'
THEN CAST(raw_value AS DECIMAL(12, 2))
END AS amount
FROM staging.import_rows;
Questions that come up
Is TRY_CAST slow?
The parse is the same work as CAST, so the difference is small next to the I/O of reading the rows. The regex variants cost more and accept less: they reject '1e5' and '+3', which a real cast would take. On PostgreSQL 16+, pg_input_is_valid(raw_value, 'numeric') is the closest native equivalent to TRY_CAST.
Keep reading
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.