// dialect comparison

Cast syntax in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

CAST runs on all five engines; the native forms add format masks, style codes or a shorter spelling.

Filed under Types & casting

The verdict

Write CAST when portability matters, but learn the native shorthand: :: in PostgreSQL, CONVERT for styled conversions in SQL Server, and the TO_ family with masks in Oracle.

Where they differ

ANSI CAST is the portable baseline: all five engines accept it. Beyond that, each engine has its own idiom, and picking the engine-native form usually buys you format masks or a shorter syntax. The examples below convert the same text to a number and back.

How each engine writes it

SQL Server

SELECT CAST('42' AS INT) AS Ansi, CONVERT(INT, '42') AS ConvertSyntax;

CAST is ANSI and has no extras. CONVERT is SQL Server-only and takes a style argument for dates. TRY_CONVERT exists for safe casts.

PostgreSQL

SELECT CAST('42' AS INTEGER), '42'::INTEGER, 42::TEXT;

The :: shorthand is PostgreSQL-specific and shorter than CAST; it binds tightly, so parenthesize around operators.

MySQL

SELECT CAST('42' AS SIGNED), CONVERT('42', SIGNED), CAST(42 AS CHAR);

CAST and CONVERT accept a fixed list of targets (SIGNED, UNSIGNED, DECIMAL, DOUBLE, CHAR, DATE, DATETIME, JSON and a few more), not column types such as INT or VARCHAR(20).

SQLite

SELECT CAST('42' AS INTEGER), CAST(42 AS TEXT);

CAST is the only explicit conversion; everything else happens silently through type affinity.

Oracle

SELECT CAST('42' AS NUMBER), TO_NUMBER('42'), TO_CHAR(42) FROM dual;

CAST exists, but the TO_NUMBER/TO_CHAR/TO_DATE family is what you reach for, because it takes format masks.

Questions that come up

Is CAST fully portable across all five engines?

For simple conversions yes: CAST(expr AS type) parses in all five. The target type names still differ per engine (INT vs INTEGER vs NUMBER), so portable SQL uses each engine's spelling.

Why does PostgreSQL have two cast syntaxes?

:: predates full ANSI support and stuck because it is short and plays well in generated SQL. CAST exists alongside it and both compile to the same operation.

Does MySQL CAST support format masks?

No. MySQL CAST only converts to fixed types. For masks you use FORMAT(), DATE_FORMAT(), LPAD() and similar functions instead.

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.