PostgreSQL & PHP Tutorials - Group Concat - Simple Example

PostgreSQL »  Group Concat In PostgreSQL
PostgreSQL »  Hints and Tips »  Group Concat In PostgreSQL

Posted By Chris Smith Posted on 16 Jun 2007, 07:55 AM
Viewing page 1 of 2
« | Back | Next | »

I found a need the other day for a function similar to the mysql 'group_concat' function.

I did a web-search and found an example but I didn't quite understand it so here's my attempt :)

First of all, we need the table and some data:

create table example(id int, val char(1));
insert into example(id, val) values (1, 'a');
insert into example(id, val) values (2, 'b');
insert into example(id, val) values (2, 'c');

The query looks rather complicated but here's the basics:

select array_to_string (
select val from example
), ','

The inside part of the query turns the 'val' entries from the table into an array, then we use the 'array_to_string' function to turn it into one big string.

We end up with:

db=# select array_to_string (
db(# array(
db(# select val from example order by val
db(# ), ','
db(# );
(1 row)

That puts all of the values from the table in an alphabetical order and in one long string.

To turn it into the output that the other example had, we need to do a bit more.

The subquery has to do a join based on the outside id (which happens to be a self join - ie back to the same database table), then we group & order the results together.

select id,
array_to_string (
select val from example inside WHERE
), ','
FROM example outside_example

That results in this being displayed:

id | count | array_to_string
1 | 1 | a
2 | 2 | b,c

Which tells us for id '1' there is 1 value called 'a'.

For id '2' there are 2 values and those values are 'b' and 'c'.
Viewing page 1 of 2
« | Back | Next | »

Avg Rating: 4
Vote Count: 38


Want to post a comment? Fill in the details below.

Your Name  : 
Your Email  : 
Your Website  : 
Spam Check! Please answer this question  : 2 + 8 =