// SQL snippet

Format money and currency values as strings in SQL

Reports and exports need money with a currency symbol and thousands separators, not a bare decimal.

Main statement
SQL Server
Также охватывает
PostgreSQL MySQL Oracle

The task

A bare decimal like 1234.5 reads badly in exports. FORMAT with the C specifier adds the currency symbol and grouping for a locale.

The snippet

Written for SQL Server. Versions for PostgreSQL, MySQL and Oracle are under Variations.

SQL Server
SELECT FORMAT(total_amount, 'C', 'en-US') AS amount_display
FROM orders;

Как это работает

FORMAT uses .NET format strings, so 'C' means currency and the third argument fixes the culture, which decides symbol placement and separators. It is convenient but slow, because each call goes through the .NET runtime; on large result sets format in the application or use CONVERT(varchar, CAST(x AS money), 1), which adds thousands separators without a symbol.

Variations

PostgreSQL

PostgreSQL
SELECT to_char(total_amount, 'FML999G999G990D00') AS amount_display
FROM orders;

MySQL

MySQL
SELECT CONCAT('$', FORMAT(total_amount, 2)) AS amount_display
FROM orders;

Oracle

Oracle
SELECT TO_CHAR(total_amount, 'FM$999G999G990D00') AS amount_display
FROM orders;

Questions that come up

Why does the PostgreSQL mask start with FM?

FM (fill mode) suppresses the padding TO_CHAR adds to fill the mask width. Without it, to_char(1234.5, 'L999G999G990D00') returns '$ 1,234.50'. L prints the currency symbol of the lc_monetary setting, so the result depends on server configuration; Oracle's mask hardcodes '$' instead.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.