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
format()
function in PostgreSQL is used to format strings in a way similar to the printf()
function in C. %s
, %I
, or %L
) to be replaced with variable values. Syntax
format(format_string [, format_arg [, ... ]])
Explanation:
The format()
function supports various format specifiers to handle different data types:
%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 FormattingThe following statement uses the FORMAT() function to format a string:
SELECT FORMAT('Hello, %s', 'Geeks!!');
Output:
Example 2: Constructing Customer Full NamesThe 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:
Important Points About FORMAT Function in PostgreSQLFORMAT()
function is variadic, meaning it can accept a varying number of arguments. I'
and 'L'
type specifiers allow the FORMAT()
function to format SQL identifiers and literals.-
' flag left-justifies the output, while the '0
'
flag pads the output with zeros instead of spaces. FORMAT()
function allows the use of positional parameters with the syntax '%n$
'
, where n
is the position of the argument in the list.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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4