Search Postgresql Archives

Re: looking for alternative to MySQL's GROUP_CONCAT function

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



<x3v0-pgsql@xxxxxxxxx> 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

---------------------------(end of broadcast)---------------------------
TIP 5: don't forget to increase your free space map settings

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux