// dialect comparison

Safe cast that returns NULL instead of an error in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

A plain CAST of 'abc' errors in SQL Server, PostgreSQL and Oracle and quietly returns 0 in MySQL and SQLite.

Filed under Types & casting

The verdict

SQL Server's TRY_CAST and Oracle's DEFAULT ... ON CONVERSION ERROR are true safe casts. PostgreSQL 16+ gets close with pg_input_is_valid inside a CASE. MySQL and SQLite never raise, so bad text arrives as 0 unless you screen it with a regex first.

Where they differ

One failed cast can kill a whole batch job. SQL Server and Oracle have a cast that returns NULL instead of failing, PostgreSQL 16 added a validity test to run before the cast, and MySQL and SQLite never fail at all, which is its own problem.

How each engine writes it

SQL Server

SELECT TRY_CAST('abc' AS INT), TRY_CONVERT(INT, 'abc');

TRY_CAST/TRY_CONVERT return NULL on failure instead of raising. Available since SQL Server 2012.

PostgreSQL

SELECT CASE WHEN pg_input_is_valid(s, 'integer') THEN s::INTEGER END
FROM (VALUES ('abc'), ('42')) AS v(s);

No TRY_CAST. pg_input_is_valid (PostgreSQL 16+) tests the text first; on older versions use a regex guard (s ~ '^[0-9]+$') or a PL/pgSQL function that traps the error. Guard a column, not a literal: PostgreSQL converts a quoted literal such as 'abc'::INTEGER while parsing, so it errors even inside a CASE branch that never runs.

MySQL

SELECT CAST('abc' AS SIGNED);

No TRY_CAST and no error either: you get 0 plus a warning, which is worse than a failure if you are not checking.

SQLite

SELECT CAST('abc' AS INTEGER);

Never errors: 'abc' becomes 0, '42abc' becomes 42. Validation is entirely your job.

Oracle

SELECT TO_NUMBER('abc' DEFAULT NULL ON CONVERSION ERROR) FROM dual;

The DEFAULT ... ON CONVERSION ERROR clause (12.2+) returns a chosen value instead of ORA-01722, and works in TO_DATE and CAST too. VALIDATE_CONVERSION('abc' AS NUMBER) returns 0 or 1 if you only want to test.

Questions that come up

Why not just try the cast and catch the error?

In a SELECT over many rows, one bad value fails the entire statement, and inside a PostgreSQL transaction it also aborts the transaction until you roll back. Screening the data or using a safe cast keeps the batch running.

What does CAST('abc' AS SIGNED) return in MySQL?

0, with only a warning. Strict mode does not change SELECT expressions, so a silent zero can flow into aggregates and reports.

Can I use regex to screen numbers in MySQL too?

Yes: WHERE col REGEXP '^[0-9]+([.][0-9]+)?$' before casting, or write a stored function mirroring TRY_CAST.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.