array_agg for PostgreSQL version < 8.4

By abdulyadi

In relation with article by Hubert Lubaczewski ‘Waiting for 8.4 – array aggregate and array unpacker’, I have the need to use the former feature for one of my project.

I have my aggregate function as follows:

CREATE AGGREGATE array_agg(anyelement) (
SFUNC=array_append,
STYPE=anyarray,
INITCOND=’{}’
);

The sample of table definition looks like:

CREATE TABLE tes
(
id integer NOT NULL,
grp integer NOT NULL,
label text NOT NULL,
CONSTRAINT tes_pkey PRIMARY KEY (id)
) WITH (OIDS=FALSE);

Populate table so it contains records:

id grp     label
1      1       ABC
2      1      DEF
3      2      GHI
4      2      JKL

Run query:
SELECT grp, array_agg(label) FROM tes GROUP BY grp;
Result:
grp array_agg
1 {ABC,DEF}
2 {GHI,JKL}

The array at the second column then -of course- can be converted to string:
SELECT grp,array_to_string( array_agg(label), ‘,’ ) FROM tes GROUP BY grp;
Result:
grp array_to_string
1 ABC,DEF
2 GHI,JKL

8 Responses to “array_agg for PostgreSQL version < 8.4”

  1. Athailah Says:

    Mantap Mr. Yadi, But I have to learn more from you, specially about QT. I very-very interested about this programing.

  2. rudy Says:

    Keren…tapi dalam english yaa om..
    tetap semangat…..

  3. Herianto Says:

    i wait the next :)

  4. Handri Says:

    Edun euy Pak Yadi Mah…….

  5. pasman Says:

    Cool ! It allows previous releases
    to be compatible with 8.4.

  6. m.dede Says:

    come

  7. Michael Tim Says:

    I love your site!

    _____________________
    Experiencing a slow PC recently? Fix it now!

  8. Random T. Says:

    I noticed that this is not the first time you mention this topic. Why have you decided to write about it again?

Leave a Reply