📜  PostgreSQL – FORMAT函数(1)

📅  最后修改于: 2023-12-03 15:03:49.303000             🧑  作者: Mango

PostgreSQL - FORMAT Function

The FORMAT function is a string function in PostgreSQL that is used to format the output of a value in a specific way. This function can be used to perform various types of string operations on textual data.

The FORMAT function syntax is as follows:

FORMAT(format_string, value1[, value2, ...])
Parameters

The FORMAT function takes the following parameters:

  • format_string: This is a string that specifies the format of the output. It can contain placeholders, which will be replaced by the values specified in the subsequent parameters.
  • value1, value2, ...: These are the values to be formatted. They can be of any data type.
Return type

The FORMAT function returns a formatted string.

Examples
Example 1: Using FORMAT function to format a string
SELECT FORMAT('Hello %s, your age is %d', 'John', 25);

Output:

Hello John, your age is 25

In this example, the FORMAT function is used to format a string. The %s and %d placeholders are used to insert the string and integer values respectively.

Example 2: Using FORMAT function to format a date
SELECT FORMAT('Today is %s', to_char(current_date, 'DD-Mon-YYYY'));

Output:

Today is 22-Jun-2021

In this example, the FORMAT function is used to format the current date. The to_char function is used to convert the date into the required format. The %s placeholder is used to insert the formatted date value.

Example 3: Using FORMAT function to format a number
SELECT FORMAT('The price is $%0.2f', 12.3456);

Output:

The price is $12.35

In this example, the FORMAT function is used to format a number. The %0.2f placeholder is used to insert the decimal number with two decimal places.

Conclusion

The FORMAT function is a useful string function in PostgreSQL that can be used to format various types of data. It provides a flexible and easy-to-use way to format data for display or other purposes.