SQL FORMAT function
Formats a value as text using .NET numeric and date format strings, with an optional culture. The most expressive formatter in SQL, and the slowest.
- 카테고리
- Strings
- Returns
string- In this category
- 18 of 172
구문
FORMAT(value, format_string [, culture])
엔진 지원
| 엔진 | Support | 메모 |
|---|---|---|
| SQL Server | 예 | Supported under this name. |
| PostgreSQL | Not built in | No built-in equivalent. |
| MySQL | Different name or syntax | MySQL's FORMAT(x, d) is a different function: it groups digits |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Not built in | No built-in equivalent. |
예시
SQL Server
SELECT FORMAT(1234.5, 'N2', 'en-us') AS money; -- 1,234.50
SQL Server
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd') AS iso_day;
MySQL
SELECT FORMAT(1234.5, 2) AS grouped; -- 1,234.50
알아 두면 좋은 정보
- FORMAT is .NET under the hood and can be an order of magnitude slower than CONVERT or CAST. Keep it off large result sets and WHERE clauses.
- Common styles: 'N2' thousands plus two decimals, 'C' currency, 'P' percent, 'd' short date. Culture argument: FORMAT(1234.5, 'N2', 'de-de') gives 1.234,50.
- Error handling is lopsided: a format string .NET rejects for that type (FORMAT(1.5, 'D')) quietly returns NULL, while passing a varchar as the value fails with Msg 8116.
- MySQL's FORMAT is not this function: it rounds and groups a number with thousands separators. See number-format.
Questions about FORMAT
Why is FORMAT so slow?
It calls into the .NET formatting layer per row, while CONVERT/CAST are native. On thousands of rows the difference is measurable. Format in the query only for final display.
Is FORMAT available outside SQL Server?
As a culture-aware formatter, no. MySQL's FORMAT groups digits only; PostgreSQL uses TO_CHAR; SQLite has printf. The .NET style strings are SQL Server specific.
How do I format a date as ISO with FORMAT?
FORMAT(d, 'yyyy-MM-dd', 'en-US'). Pass the culture: without it FORMAT uses the session language, and a culture with a non-Gregorian calendar changes the date itself: FORMAT(d, 'yyyy-MM-dd', 'ar-SA') returns a Hijri date like 1447-07-16. CONVERT(char(10), d, 23) is the cheaper ISO route.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Convert a number to formatted text in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Format money and currency values as strings in SQL Snippet
- Grant SELECT on all tables Snippet
- List materialized views and refresh times Snippet
- Move a table between schemas Snippet
- Pad numbers with leading zeros in SQL Snippet
Cheat sheets for the engines that have it: SQL Server, 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.