Re: looking for alternative to MySQL's GROUP_CONCAT function

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: x3v0-pgsql(at)yahoo(dot)com
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: looking for alternative to MySQL's GROUP_CONCAT function
Date: 2005-10-21 20:12:19
Message-ID: 25173.1129925539@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

<x3v0-pgsql(at)yahoo(dot)com> writes:
> I'm looking into PostgreSQL. Coming from a MySQL
> background, I have made heavy use of its very useful
> GROUP_CONCAT function. You can read about the function
> here:
> http://dev.mysql.com/doc/refman/4.1/en/group-by-functions.html
> Is there a PostgreSQL alternative to GROUP_CONCAT?

In Postgres it's customary to build this sort of thing out of spare
parts. The basic spare part is a user-defined aggregate. You can
make an aggregate over the built-in concatenation function:

CREATE AGGREGATE concat (
BASETYPE = text,
SFUNC = textcat,
STYPE = text
);

This does the basic task of concatenating the values found in a table
group, but it doesn't supply any separator, so more likely you'd want
to write a custom function that inserts a separator and then aggregate
with that:

create function textcatspace(text,text) returns text as $$
select $1 || ' ' || $2
$$ language sql strict immutable;

CREATE AGGREGATE concat (
BASETYPE = text,
SFUNC = textcatspace,
STYPE = text
);

(NB: the "strict" bit is essential to get this to match MySQL's
semantics for NULLs in group_concat.)

We don't unfortunately have any easy way to pass in different separator
values --- you'd need to create a distinct function and aggregate for
each separator string you want. Also, a function in plpgsql might be
more efficient than one in SQL.

The other part this isn't handling is controlling the order in which the
inputs are concatenated. You can find that discussed in the archives:

http://archives.postgresql.org/pgsql-general/2005-09/msg00034.php

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message David Fetter 2005-10-21 20:25:09 Re: looking for alternative to MySQL's GROUP_CONCAT function
Previous Message Michael Fuhr 2005-10-21 20:12:10 Re: Select all invalid e-mail addresses