// dialect comparison

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

Five engines, four different formatting idioms for the same 1,234,567.89.

Filed under Types & casting

The verdict

There is no portable formatted conversion: TO_CHAR masks in PostgreSQL and Oracle, a costly FORMAT in SQL Server, a FORMAT in MySQL that always adds separators, and printf-style FORMAT in SQLite.

Where they differ

Casting a number to text is easy; formatting it with thousand separators and decimals is where the dialects diverge completely. Each row formats the same number to 1,234,567.89 in its engine's native idiom.

How each engine writes it

SQL Server

SELECT FORMAT(1234567.891, 'N2');

FORMAT uses .NET format strings ('N2' = thousands separators and 2 decimals) and calls into the CLR for every row, so it is much slower than CONVERT(VARCHAR, x), which has no mask.

PostgreSQL

SELECT TO_CHAR(1234567.891, 'FM9,999,999.00');

Mask syntax: 9 is a digit, 0 is a forced digit, FM trims padding. TO_CHAR is the idiomatic tool.

MySQL

SELECT FORMAT(1234567.891, 2);

FORMAT always adds thousands separators and rounds to the given decimals; CAST(42 AS CHAR) is the plain, maskless conversion.

SQLite

SELECT FORMAT('%,.2f', 1234567.891);

FORMAT (3.38+, the new name for printf) takes C-style masks. The ',' flag is a SQLite extension that adds thousands separators, so this returns 1,234,567.89.

Oracle

SELECT TO_CHAR(1234567.891, 'FM9,999,999.00') FROM dual;

Same mask family as PostgreSQL. Group separator and decimal character follow NLS settings.

Questions that come up

Why does my TO_CHAR output have leading spaces?

9 placeholders reserve room for a sign and pad to the mask width. Prefix the mask with FM to trim the padding.

How do I control the decimal character?

In Oracle and PostgreSQL the D and G mask characters follow NLS_NUMERIC_CHARACTERS and lc_numeric. MySQL's FORMAT takes an optional locale, FORMAT(x, 2, 'de_DE'), and defaults to en_US. SQL Server's FORMAT takes an optional culture such as 'de-DE' and otherwise follows the session language.

Is SQL Server FORMAT() suitable for big result sets?

No. It invokes the .NET runtime per row. Use CONVERT for plain casts and reserve FORMAT for display-level queries.

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.