The Wayback Machine - https://web.archive.org/web/20241004173614/https://www.geeksforgeeks.org/postgresql-format-function/
Open In App

PostgreSQL – FORMAT Function

Last Updated : 17 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In PostgreSQL, the FORMAT() function is a powerful tool for formatting arguments based on a specified format string.

Let us better understand the FORMAT() Function in PostgreSQL, its syntax, components, and practical usage to help you leverage this function effectively.

Syntax

FORMAT(format_string [, format_argument [, ....] ])

Let’s analyze the above syntax:

  • The FORMAT() function is variadic, meaning, users can supply the arguments as an array marked with the VARIADIC keyword.
  • The FORMAT() function considers the array’s elements as normal arguments and it treats NULL as an array of zero elements.

Parameters:

1. ‘format_string’

  • The ‘format_string’ sets the behaviour of the resulting formatted string. It also has text and format specifiers. In this function, the text arguments are copied directly to the result string and the format specifiers are placeholders for the arguments.

Syntax of the format specifier:

%[position][flags][width]type

Note that a format specifier begins with a “%” and it has three optional components position, flags, width, and a required component type.

2. ‘position’

  • It is used to set the argument that is to be inserted in the result string. The position is in the form of ‘n$’ where ‘n’ is the argument index. The first argument starts from 1. The default is the next argument in the list if the position component is not set.

3.  ‘flags’

  • This component is used in conjunction with the width field, for instance, the flags can accept a minus sign (-) that instructs the format specifier’s output to be left-justified.

4. ‘width’

  • This optional argument sets the minimum number of characters for the format specifier’s output. If the string is shorter than the specified width, padding fills the empty spaces. If longer, the string remains unchanged.

The width argument can hold the following values:

  • A positive integer value.
  • An asterisk (*) to use the next function argument as the width.
  • A string of the form *n$ to use the nth function argument as the width.

5. ‘type’

  • It is used to define the type of the output string from the format specifier.

It can hold the following values:

  • ‘s’: It formats the argument value as a string. NULL values are treated as an empty strings.
  • ‘I’: It treats the argument value as an SQL identifier.
  • ‘L’: It makes the argument value as an SQL literal.
  • '%%': Includes the % sign.

‘I‘ and ‘L‘ are generally used for constructing dynamic SQL statements.

6. ‘format_arg’

  • The users pass a number of format arguments to the ‘FORMAT’() function.

Return value

  • The FORMAT() function returns a formatted string.

PostgreSQL FORMAT Function Examples

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’s full names from first names and last names from the customers table of the sample database, ie, 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

  • The FORMAT() function is variadic, meaning it can accept a varying number of arguments.
  • The ‘I' and ‘L' type specifiers allow the FORMAT() function to format SQL identifiers and literals.
  • The ‘-‘ flag left-justifies the output, while the ‘0' flag pads the output with zeros instead of spaces.
  • The FORMAT() function allows the use of positional parameters with the syntax ‘%n$', where n is the position of the argument in the list.


Similar Reads

PostgreSQL - Connect To PostgreSQL Database Server in Python
The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python setup.py build sudo python setup.py installCreate a
4 min read
PostgreSQL - Export PostgreSQL Table to CSV file
In this article we will discuss the process of exporting a PostgreSQL Table to a CSV file. Here we will see how to export on the server and also on the client machine. For Server-Side Export: Use the below syntax to copy a PostgreSQL table from the server itself: Syntax: COPY Table_Name TO 'Path/filename.csv' CSV HEADER; Note: If you have permissio
2 min read
PostgreSQL - Installing PostgreSQL Without Admin Rights on Windows
If you are a part of a corporation, it is highly unlikely that you have the admin privileges to install any external software. But the curious souls that all software developers are, in this article, we will see the detailed process of installation of PostgreSQL without having administrator rights on our Windows machine. Installation: Follow the be
3 min read
PostgreSQL - CONCAT_WS Function
In PostgreSQL, the CONCAT_WS function is used to concatenate strings with a separator. Like the CONCAT function, the CONCAT_WS function is also variadic and ignored NULL values. The following illustrates the syntax of the CONCAT_WS function. Syntax: CONCAT_WS(separator, string_1, string_2, ...); Let's analyze the above syntax: The separator is a st
1 min read
PostgreSQL - ARRAY_AGG() Function
PostgreSQL ARRAY_AGG() function is an aggregate function that accepts a set of values and returns an array where each value in the input set is assigned to an element of the array. SyntaxARRAY_AGG(expression [ORDER BY [sort_expression {ASC | DESC}], [...])Where, The ORDER BY clause is a voluntary clause. It specifies the order of rows that are proc
2 min read
PostgreSQL - LAG Function
In PostgreSQL, the LAG() function is a powerful window function that allows you to access a row that comes exactly before the current row at a specified physical offset. This function is particularly useful for comparing the values of the current row with the previous row, enabling a range of analytical queries. SyntaxThe following shows the syntax
3 min read
PostgreSQL - STRING_AGG() Function
The STRING_AGG() function in PostgreSQL is a powerful aggregate function used to concatenate a list of strings with a specified separator. This function is essential for combining string values from multiple rows into a single string, making data aggregation more efficient and readable. Let us get a better understanding of the syntax, usage, and pr
3 min read
PostgreSQL - REPLACE() Function
In PostgreSQL, the REPLACE function is an essential string manipulation tool that allows users to search for and replace all occurrences of a specific substring within a given string. This function is particularly useful for data cleaning, formatting, and updating textual data. Let us get a better understanding of the REPLACE Function in PostgreSQL
2 min read
PostgreSQL - RANK Function
The RANK() Function in PostgreSQL is a powerful tool used to assign a rank to each row in a query result set within a specified partition. The rank of the first row within each partition is always 1. This function is particularly useful for ranking results, such as finding the top performers or identifying items with the highest values. Let us get
3 min read
PostgreSQL - ROW_NUMBER Function
The ROW_NUMBER() function in PostgreSQL is a powerful tool used to assign a unique integer to every row returned by a query. This function is especially useful for tasks that require numbering rows in the result set, such as generating sequential numbers, implementing pagination, or creating ordered lists. Let us get a better understanding of the R
3 min read
PostgreSQL - CREATE FUNCTION Statement
PostgreSQL allows developers to create user-defined functions to encapsulate reusable logic. The CREATE FUNCTION statement is used for this purpose, supporting various procedural languages, with plpgsql being one of the most commonly used. Let us look at the syntax, structure, and practical use of CREATE FUNCTION Statement in PostgreSQL, using the
3 min read
PostgreSQL - DATE_TRUNC Function
The DATE_TRUNC function in PostgreSQL is a powerful tool used to truncate a timestamp or interval to a specified level of precision. This function is particularly useful for handling time-based data, enabling more effective data grouping and manipulation. Let us get a better understanding of the DATE_TRUNC function, its syntax, and practical exampl
2 min read
PostgreSQL - REGEXP_REPLACE Function
The PostgreSQL REGEXP_REPLACE() function is used to replace substrings within a string that match a POSIX regular expression with a specified replacement substring. Let us better understand the REGEXP_REPLACE() function in PostgreSQL from this article. Syntax The syntax for REGEXP_REPLACE() in PostgreSQL is as follows: REGEXP_REPLACE(source, patter
2 min read
PostgreSQL- CONCAT Function
In PostgreSQL, the CONCAT function is a powerful tool used to concatenate two or more strings into a single string. Let us get a better understanding of the usage, syntax, and practical examples of the CONCAT function, enhancing your PostgreSQL skills. SyntaxCONCAT(string_1, string_2, ...)Let's analyze the above syntax: String Convertible Arguments
2 min read
PostgreSQL - TRIM Function
The TRIM() function in PostgreSQL is an essential tool for data cleansing, allowing you to remove unwanted characters from the beginning, end, or both ends of a string. By default, it removes spaces, but you can specify any character to be removed. Let us get a better understanding of the usage, syntax, and practical examples of the TRIM() function
2 min read
PostgreSQL - Function Returning A Table
Creating custom functions that return tables is handy for complex queries and dynamic data processing. In this article, we will look into developing functions that return a table in PostgreSQL. We will use the film table in the sample database for the demonstration. Creating a Function to Return Films Based on Title PatternThe following function re
3 min read
PostgreSQL - CURRENT_TIME Function
The PostgreSQL CURRENT_TIME function returns the current time and the current time zone. This function is handy when you need to work with time-sensitive data in your database applications. Let us better understand the CURRENT_TIME Function in PostgreSQL from this article. SyntaxCURRENT_TIME(precision)Parameter:Precision Argument: The precision arg
3 min read
PostgreSQL - CURRENT_DATE Function
The PostgreSQL CURRENT_DATE function is used to retrieve the current date. It’s a simple and effective way to ensure your database operations are using the correct date, particularly for applications that need timestamp records. Let us better understand the CURRENT_DATE Function in PostgreSQL from this article. SyntaxCURRENT_DATEReturn value: The '
2 min read
PostgreSQL - POSITION Function
The PostgreSQL POSITION() function is used to find the location of a substring within a string. This function is particularly useful for text manipulation and searching operations within your database. Let us better understand the POSITION Function in PostgreSQL from this article. SyntaxPOSITION(substring IN string)Parameters:Let's analyze the abov
2 min read
PostgreSQL - CUME_DIST Function
The PostgreSQL CUME_DIST() function is a powerful analytical tool used to determine the relative position of a value within a set of given values. This function helps compute the cumulative distribution of values in a result set, which can be particularly useful in statistical analysis and reporting. Let us better understand the CUME_DIST Function
3 min read
PostgreSQL- LPAD Function
The LPAD() function in PostgreSQL is a powerful tool for padding a string to the left, ensuring it reaches a specified length by filling it with a designated character or characters. This function can be particularly useful in data formatting and report generation. Let us better understand the LPAD Function in PostgreSQL from this article. SyntaxLP
2 min read
PostgreSQL MAX() Function
The MAX() function in PostgreSQL is a versatile aggregate function used to determine the maximum value within a set of values. This function can be employed in various SQL clauses, including SELECT, WHERE, and HAVING, making it a powerful tool for data analysis and reporting. Let us better understand the MAX() Function in PostgreSQL to better under
2 min read
PostgreSQL MIN() Function
The MIN() function in PostgreSQL is an essential aggregate function that returns the minimum value in a set of values. This function is highly useful in various data analysis and reporting tasks, allowing you to quickly identify the smallest values in your datasets. Let us better understand the MIN() Function in PostgreSQL to better understand the
2 min read
PostgreSQL - NULLIF() Function
Handling null values effectively is crucial in database management, and PostgreSQL offers powerful functions like NULLIF to address this issue. These functions are particularly useful in SELECT statements, allowing you to efficiently manage null and empty values. Let's explore the PostgreSQL NULLIF function, including its syntax, usage, and practic
3 min read
PostgreSQL DATE_PART Function
Handling dates and times efficiently is crucial for database management, and PostgreSQL offers robust functions like DATE_PART() to extract specific subfields from date and time values. Let us better understand the syntax, usage, and practical examples of the DATE_PART() function, helping you master its application in PostgreSQL. SyntaxDATE_PART(fi
2 min read
PostgreSQL - Substring Function
In PostgreSQL, the SUBSTRING function is a versatile tool used to extract a specific portion of a string. This function is particularly useful for manipulating textual data, allowing you to retrieve substrings based on defined criteria. Let us get a better understanding of the Substring Function in PostgreSQL from this article. SyntaxSUBSTRING ( st
2 min read
PostgreSQL - FIRST_VALUE() Function
The FIRST_VALUE() function in PostgreSQL retrieves the first value in an ordered set of rows within a partition of a query result. This function is useful for analytical purposes, allowing you to fetch specific insights or data points from structured datasets. Let us better understand the FIRST_VALUE Function in PostgreSQL from this article. Syntax
3 min read
PostgreSQL - DROP FUNCTION
In PostgreSQL, the DROP FUNCTION statement is essential for removing functions from your database. Let us learn more about the syntax and the detailed examples to ensure you understand how to use this statement effectively. SyntaxDROP FUNCTION [IF EXISTS] function_name(argument_list) [CASCADE | RESTRICT]; Parameters:Let's analyze the above syntax:
4 min read
PostgreSQL - SPLIT_PART Function
The PostgreSQL SPLIT_PART() function is a powerful tool for splitting strings based on a specific delimiter and returning a specified substring (nth substring). Let us learn about its syntax and practical examples to enhance your data manipulation skills in PostgreSQL. SyntaxSPLIT_PART(string, delimiter, position)ParametersLet's analyze the above s
2 min read
PostgreSQL - LEAD Function
In PostgreSQL, the LEAD() function is a powerful window function used to access a row that follows the current row at a specific physical offset. This function is generally employed to compare the value of the current row with the value of the next row following the current row. Let us better understand the LEAD Function in PostgreSQL from this art
3 min read