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.
Text '42' becomes 42 everywhere, but 'abc' raises an error in three engines and quietly becomes 0 in two.
Filed under Types & casting
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.
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.
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.
SELECT '42'::INTEGER + 1;
Use NUMERIC instead of INTEGER for decimals: '42'::NUMERIC. 'abc' raises an error.
SELECT CAST('42' AS SIGNED) + 1;
'42abc' casts to 42 and 'abc' to 0, each with warning 1292 instead of an error.
SELECT CAST('42' AS INTEGER) + 1;
CAST reads the longest numeric prefix: '42abc' becomes 42, 'abc' becomes 0. It never errors.
SELECT TO_NUMBER('42') + 1 FROM dual;
TO_NUMBER accepts a mask: TO_NUMBER('1,234', '9G999'). Unparseable text raises ORA-01722.
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.
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.
No, in any engine. Strip them yourself or use a format mask such as Oracle's TO_NUMBER('$1,234', 'L9G999').
A plain CAST of 'abc' errors in SQL Server, PostgreSQL and Oracle and quietly returns 0 in MySQL and SQLite.
CAST runs on all five engines; the native forms add format masks, style codes or a shorter spelling.
Five engines, four different formatting idioms for the same 1,234,567.89.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.