Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two arrays and pick only the non matching elements In postgres

Tags:

postgresql

How can I pick only the non matching elements between two arrays.

Example:

base_array [12,3,5,7,8] temp_array [3,7,8] 

So here I want to compare both the arrays and remove the matching elements from the base array.

Now base_array should be like [12,5]

like image 998
ggvvkk Avatar asked Jun 30 '11 09:06

ggvvkk


People also ask

How do you compare two arrays if they are equal or not?

Check if two arrays are equal or not using Sorting Follow the steps below to solve the problem using this approach: Sort both the arrays. Then linearly compare elements of both the arrays. If all are equal then return true, else return false.

How do I compare two arrays of elements?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

What is Unnest in PostgreSQL?

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

How do you check if two arrays matches with each other?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

I'd approach this with the array operator.

select array(select unnest(:arr1) except select unnest(:arr2)); 

If :arr1 and :arr2 don't intersect, using array_agg() leads to a null.

like image 180
Denis de Bernardy Avatar answered Oct 04 '22 09:10

Denis de Bernardy