// dialect comparison

Cast text to a number in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

Text '42' becomes 42 everywhere, but 'abc' raises an error in three engines and quietly becomes 0 in two.

Filed under Types & casting

The verdict

Identical syntax, opposite failure modes: SQL Server, PostgreSQL and Oracle refuse bad input, while MySQL and SQLite quietly give you 0 or the numeric prefix. Validate in the app or use a safe cast.

Where they differ

Every engine converts text to numbers, and every engine has different rules for what happens when the text is not a number. The casts below are the happy path; see safe-cast for what 'abc' does.

How each engine writes it

SQL Server

SELECT CAST('42' AS INT) + 1;

Leading and trailing spaces are tolerated. 'abc' raises a conversion error, and so does '4.2' when the target is INT; cast to DECIMAL for decimals.

PostgreSQL

SELECT '42'::INTEGER + 1;

Use NUMERIC instead of INTEGER for decimals: '42'::NUMERIC. 'abc' raises an error.

MySQL

SELECT CAST('42' AS SIGNED) + 1;

'42abc' casts to 42 and 'abc' to 0, each with warning 1292 instead of an error.

SQLite

SELECT CAST('42' AS INTEGER) + 1;

CAST reads the longest numeric prefix: '42abc' becomes 42, 'abc' becomes 0. It never errors.

Oracle

SELECT TO_NUMBER('42') + 1 FROM dual;

TO_NUMBER accepts a mask: TO_NUMBER('1,234', '9G999'). Unparseable text raises ORA-01722.

Questions that come up

Why did my string become 0 in MySQL?

CAST('abc' AS SIGNED) yields 0 and only raises a warning, even in strict mode, because strict mode governs writes rather than SELECT expressions. Check warnings or guard with a regex.

How do I parse a decimal string?

Cast to NUMERIC in PostgreSQL, DECIMAL in SQL Server and MySQL (CAST('4.2' AS DECIMAL(9,2))), REAL in SQLite, and TO_NUMBER('4.2') in Oracle.

Does CAST strip currency symbols?

No, in any engine. Strip them yourself or use a format mask such as Oracle's TO_NUMBER('$1,234', 'L9G999').

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.