// strings reference

SQL FORMAT number formatting

Formats values as display text. SQL Server and MySQL format numbers; PostgreSQL and SQLite use the name for printf-style composition.

類別
Strings
Returns
string
In this category
109 of 172

語法

FORMAT(value, format [, culture])
MySQL: FORMAT(number, decimals [, locale])

Each block is a separate form. The support table and the examples show which engine takes which.

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
PostgreSQL Different name or syntax format() is printf-style text composition; TO_CHAR formats numbers.
MySQL 是 Supported under this name.
SQLite Different name or syntax format() (3.38+) is an alias of printf; printf('%,d', n) adds thousands separators.
Oracle Different name or syntax No FORMAT; TO_CHAR(value, '9G999D99') formats numbers.

範例

SQL Server

SELECT FORMAT(total, 'N2') AS total_fmt
FROM orders;

MySQL

SELECT FORMAT(1234.5, 2) AS price_fmt;  -- 1,234.50

PostgreSQL

SELECT format('%s sold %s units', product, units) AS line
FROM sales;

小知識

  • SQL Server's FORMAT takes .NET format strings ('N2' for grouped decimals, 'C' for currency, 'yyyy-MM-dd' for dates) and runs through the CLR, so it is much slower than CONVERT on large result sets.
  • MySQL's FORMAT(number, 2) rounds and inserts thousands separators, producing '1,234.50'. The result is text, so sorting or comparing it gives string order.
  • PostgreSQL's format('%s ...', args) never formats numbers with separators; for that use TO_CHAR(value, 'FM9,999.00').

Questions about FORMAT

Why does ORDER BY FORMAT(...) sort wrong?

FORMAT returns a string, so '10,000.00' sorts before '9,999.00' ('1' comes before '9'). Order by the numeric column and format only in the SELECT list.

Is FORMAT the same function in every engine?

No. SQL Server and MySQL format numbers for display; PostgreSQL's format() and SQLite's format() compose strings printf-style. Oracle has no FORMAT.

What should I use for locale-aware currency?

MySQL accepts a locale: FORMAT(x, 2, 'de_DE') gives '1.234,50'. SQL Server takes a culture: FORMAT(x, 'C', 'de-DE'). PostgreSQL's TO_CHAR uses the L, D and G codes, which follow lc_monetary and lc_numeric.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.