Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of two arrays in PostgreSQL without unnesting

I have two arrays in PostgreSQL that I need to union. For example:

{1,2,3} union {1,4,5} would return {1,2,3,4,5}

Using the concatenate (||) operator would not remove duplicate entries, i.e. it returns {1,2,3,1,4,5}

I found one solution on the web, however I do not like how it needs to unnest both arrays: select ARRAY(select unnest(ARRAY[1,2,3]) as a UNION select unnest(ARRAY[2,3,4,5]) as a)

Is there an operator or built-in function that will cleanly union two arrays?

like image 500
MrGlass Avatar asked Jun 10 '14 18:06

MrGlass


People also ask

What is Unnest in PostgreSQL?

Unnest function generates a table structure of an array in PostgreSQL. Unnest array function is beneficial in PostgreSQL for expanding the array into the set of values or converting the array into the structure of the rows. PostgreSQL offers unnest() function.

What is Array_agg in Postgres?

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.

How do I declare a string array in PostgreSQL?

Syntax. In the above syntax, we can declare a String Array data type at the time of table creation. Where table name is the specified table name that we need to create and column 1, column 2, and column n declared with the data type of array and it separated by using a comma.

Which of the following will be used to search data in the array in PostgreSQL?

The elements of the array can be retrieved using the SELECT statement. The values of the array column can be enclosed within square brackets [] or curly braces {}. We can search for array column values using the ANY() function.


Video Answer


1 Answers

If your problem is to unnest twice this will unnest only once

select array_agg(a order by a)
from (
    select distinct unnest(array[1,2,3] || array[2,3,4,5]) as a
) s;
like image 121
Clodoaldo Neto Avatar answered Oct 28 '22 18:10

Clodoaldo Neto