How to Use string_agg()

«««< HEAD Postgres provides a function called string_agg, (in fact there are two functions with the same meaning, one is an aggregate function and the other is a window function). Here we cover the aggregated function. The idea is to concat several strings, from different rows separated by a specified separator.

Postgres provides a function called string_agg, (in fact there are two functions with the same meaning, one is an aggregate function and the other is a window function). Here we cover the aggregated function. The idea is to concat several strings, from different rows separated by a specified separator.

master

create table teams (team_name text, team_member text);
insert into teams values (‘Barcelona’,’Messi’), (‘Barcelona’,’Piquet’),
                         	 (‘Barcelona’,’Xavi’);
insert into teams values (‘Real Madrid’,’Ronaldo’), (‘Real Madrid’,’Benzema’),
                         	 (‘Real Madrid’,’Ramos’);

This is our base table:

select * from teams;
team_name team_member
Real Madrid Ronaldo
Real Madrid Benzema
Real Madrid Ramos
Barcelona Messi
Barcelona Piquet
Barcelona Xavi

This function concatenates the values of a given column using a separator, due string_agg is an aggregate function, the group by clause plays an important role to define what rows are grouped.

select team_name, string_agg(team_member,', ') from teams group by team_name;
team_name string_agg(team_member,’, ‘)
Real Madrid Ronaldo, Benzema, Ramos
Real Madrid Messi, Piquet, Xavi

The group by team_name clause creates groups of rows with the same value in team_name, then all the members of the same team are concatenated in the same string.

IN THIS PAGE