Skip to main content
Documents
Clauses StatementsKeywordsExpressionsFunctionsIndexesPerformance Optimization

MySQL FORMAT Expressions

The `FORMAT` expression in MySQL is used to format numbers to a specified number of decimal places, adding commas as thousands separators. It is particularly useful for enhancing the readability of numerical data in SQL queries.

Usage

The `FORMAT` expression is typically used when you need to display numbers in a more human-readable format, especially for financial and statistical reports. It converts a number to a string with a specified number of decimal places, including locale-based thousands separators.


FORMAT(number, decimal_places)

In this syntax, `number` is the numeric value to be formatted, and `decimal_places` specifies the number of decimal places to retain.

Examples

1. Basic Formatting


SELECT FORMAT(1234567.89, 2);

This example formats the number `1234567.89` to `1,234,567.89`, adding commas as thousands separators and retaining two decimal places.

2. Formatting with Zero Decimals


SELECT FORMAT(98765.4321, 0);

Here, the number `98765.4321` is formatted as `98,765`, rounding the number to the nearest whole number and removing decimal places.

3. Formatting with Locale


SELECT FORMAT(1234567.89, 2, 'de_DE');

This example formats `1234567.89` to `1.234.567,89` using the German locale, which uses a period as a thousands separator and a comma as a decimal point.

Tips and Best Practices

  • Consider Performance. Using `FORMAT` can impact performance when applied to large datasets, so use it judiciously. In cases where performance is critical, consider formatting numbers in your application layer instead.
  • Locale Usage. Always specify a locale if you need specific formatting conventions for different countries.
  • Use for Display Only. Remember that `FORMAT` returns a string, so it should be used for display purposes rather than further numerical calculations.
  • Consistent Decimal Places. Ensure consistency in the number of decimal places across your dataset for uniformity and clarity.
  • Error Handling. If non-numeric values are passed to the `FORMAT` function, it will result in an error. Similarly, using an invalid locale string will default to the standard locale. Always validate inputs to prevent errors.

SQL Upskilling for Beginners

Gain the SQL skills to interact with and query your data.
Start Learning for Free