SQL MySQL FORMAT function
Rounds and groups a number for display: FORMAT(1234.5, 2) returns '1,234.50'. A third argument picks the locale's separators.
- 類別
- Strings
- Returns
string- In this category
- 19 of 172
語法
FORMAT(number, decimals [, locale])
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Not built in | No built-in equivalent. |
| PostgreSQL | Not built in | No built-in equivalent. |
| MySQL | 是 | Supported under this name. |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Not built in | No built-in equivalent. |
範例
MySQL
SELECT FORMAT(1234567.891, 2) AS grouped; -- 1,234,567.89
MySQL
SELECT FORMAT(1234.5, 2, 'de_DE') AS german; -- 1.234,50
小知識
- A negative decimals value is treated as 0, so FORMAT(1234.5, -1) is '1,235'. Rounding is half away from zero: FORMAT(2.5, 0) is '3' and FORMAT(-2.5, 0) is '-3'.
- The result is a string with separators; arithmetic on it or storing it re-parses. Keep raw numbers in columns, FORMAT only for display.
- Locale strings use an underscore: FORMAT(1234.5, 2, 'de_DE') gives '1.234,50'.
- SQL Server's FORMAT is a different function that takes .NET patterns. PostgreSQL's nearest equivalent is TO_CHAR(number, 'FM9,999.00').
Questions about FORMAT (MySQL)
Does MySQL FORMAT return a number?
No, a string. Separators are not valid in a numeric literal. Casting it back drops the grouping, so format only at the last step.
How is this different from SQL Server FORMAT?
MySQL's version only does digits-and-separators rounding. SQL Server's takes .NET patterns like 'N2' and 'C' plus a culture, and also formats dates.
Can I use FORMAT in a WHERE clause?
It works but defeats indexes and runs per row. Filter on the raw numeric column instead.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: MySQL.
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.