PostgreSQL – STRING_AGG Function

The string_agg function in PostgreSQL is used to concatenate strings from a group of rows into a single string, with a specified delimiter between the concatenated values.

Here is the syntax of the string_agg function:

string_agg(expression, delimiter)

The expression parameter specifies the column or expression that you want to concatenate, and the delimiter parameter specifies the character or string that you want to use to separate the concatenated values.

The expression can be any valid expression that returns a string or can be cast to a string, including columns, string literals, and functions that return strings.

Below is an example of using the string_agg function to aggregate names of employees into a single comma-separated string:

SELECT string_agg(name, ', ') AS all_names
FROM employees;

This will concatenate all the names from the employees table and separate them with a comma and return the result in a column named all_names.

Similar Posts