Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge all integer arrays from all records into single array in postgres

I have a column which is of type integer array. How can I merge all of them into a single integer array?

For example: If I execute query:

select column_name from table_name 

I get result set as:

-[RECORD 1]---------- column_name | {1,2,3} -[RECORD 2]---------- column_name | {4,5} 

How can I get {1,2,3,4,5} as final result?

like image 541
user1465266 Avatar asked Mar 27 '14 03:03

user1465266


People also ask

What is Unnest in PostgreSQL?

PostgreSQL UNNEST() function This function is used to expand an array to a set of rows.

What is array AGG in PostgreSQL?

PostgreSQL ARRAY_AGG() function is an aggregate function that accepts a set of values and returns an array where each value in the input set is assigned to an element of the array. Syntax: ARRAY_AGG(expression [ORDER BY [sort_expression {ASC | DESC}], [...]) The ORDER BY clause is an voluntary clause.


2 Answers

You could use unnest to open up the arrays and then array_agg to put them back together:

select array_agg(c) from (   select unnest(column_name)   from table_name ) as dt(c); 
like image 153
mu is too short Avatar answered Sep 21 '22 09:09

mu is too short


Define a trivial custom aggregate:

CREATE AGGREGATE array_cat_agg(anyarray) (   SFUNC=array_cat,   STYPE=anyarray ); 

and use it:

WITH v(a) AS ( VALUES (ARRAY[1,2,3]), (ARRAY[4,5,6,7])) SELECT array_cat_agg(a) FROM v; 

If you want a particular order, put it within the aggregate call, i.e. array_cat_agg(a ORDER BY ...)

This is roughly O(n log n) for n rows (I think) O(n²) so it is unsuitable for long sets of rows. For better performance you'd need to write it in C, where you can use the more efficient (but horrible to use) C API for PostgreSQL arrays to avoid re-copying the array each iteration.

like image 22
Craig Ringer Avatar answered Sep 21 '22 09:09

Craig Ringer