Skip to content

Instantly share code, notes, and snippets.

@aaronpuchert
Created July 21, 2013 17:22
Show Gist options
  • Save aaronpuchert/6049219 to your computer and use it in GitHub Desktop.
Save aaronpuchert/6049219 to your computer and use it in GitHub Desktop.
This is a group_concat(int) replacement for PostgreSQL.
CREATE OR REPLACE FUNCTION group_concat_iterate(_state INTEGER[], _value INTEGER)
RETURNS INTEGER[] AS
$BODY$
SELECT
CASE
WHEN $1 IS NULL THEN ARRAY[$2]
ELSE $1 || $2
END
$BODY$
LANGUAGE SQL VOLATILE;
CREATE OR REPLACE FUNCTION group_concat_finish(_state INTEGER[])
RETURNS text AS
$BODY$
SELECT array_to_string($1, ',')
$BODY$
LANGUAGE SQL VOLATILE;
CREATE AGGREGATE group_concat(int) (SFUNC = group_concat_iterate, STYPE = INTEGER[], FINALFUNC = group_concat_finish);
@aaronpuchert
Copy link
Author

Adapted from Explain Extended. Here we want to concatenate integers.

@scalahub
Copy link

scalahub commented Dec 4, 2017

Here is a better solution (Not mine!)
https://stackoverflow.com/a/47638417/243233

CREATE OR REPLACE FUNCTION _group_concat_finalize(anyarray)
RETURNS text AS $$
SELECT array_to_string($1,',')
$$ IMMUTABLE LANGUAGE SQL;

CREATE AGGREGATE group_concat(anyelement) (
SFUNC=array_append,
STYPE=anyarray,
FFUNC=_group_concat_finalize,
INITCOND='{}'
);

SELECT group_concat(x) FROM foo;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment