PostgreSQL FORMAT Function (original) (raw)

Last Updated : 15 Jul, 2025

The PostgreSQL format() function is a powerful tool for string formatting by allowing developers to insert variables into strings using format specifiers like%s** , %I , and %L . This function is especially useful for building dynamic **SQL queries and ensuring proper formatting of identifiers.

It simplifies complex string manipulations and enhances security by preventing **SQL injection. In this article, We will learn about the **FORMAT Function in **PostgreSQL in detail by understanding various aspects.

PostgreSQL Format() Function

**Syntax

format(format_string [, format_arg [, ... ]])

**Explanation:

Supported Format Specifiers

The format() function supports various format specifiers to handle different data types:

Specifier Description
%s Replaces with a string.
%I Replaces with an identifier (table or column name).
%L Replaces with a literal (safely quoted).
%t Replaces with a Boolean.
%D Replaces with a numeric, double-precision number.

Examples of Using the format() Function

Let us take a look at some of the examples of FORMAT Function in PostgreSQL to better understand the concept.

**Example 1: Simple String Formatting

The following statement uses the FORMAT() function to format a string:

SELECT FORMAT('Hello, %s', 'Geeks!!');

**Output:

PostgreSQL FORMAT Function Example

**Example 2: Constructing Customer Full Names

The following statement uses the FORMAT() function to construct customer' full names from first names and last names from the **customers table of the sample database which is **dvdrental:

SELECT
FORMAT('%s, %s', last_name, first_name) full_name
FROM
customer;
ORDER BY
full_name;

**Output:

PostgreSQL FORMAT Function Example

Important Points About FORMAT Function in PostgreSQL

Conclusion

The PostgreSQL format() function is a versatile tool for formatting strings, making it an excellent choice for dynamic SQL generation and improving code readability. Whether you’re dealing with simple text or complex identifiers and literals, the format() function provides a robust way to customize your outputs and queries.