I have a table with 4 array columns.. the results are like:
ids signed_ids new_ids new_ids_signed
{1,2,3} | {2,1,3} | {4,5,6} | {6,5,4}
Anyway to compare ids and signed_ids so that they come out equal, by ignoring the order of the elements?
The simplest thing to do is sort them and compare them sorted. See sorting arrays in PostgreSQL.
Given sample data:
the best thing to do is to if the array entries are always integers is to use the intarray extension, as Erwin explains in his answer. It’s a lot faster than any pure-SQL formulation.
Otherwise, for a general version that works for any data type, define an
array_sort(anyarray):and use it sort and compare the sorted arrays:
There’s an important caveat:
will be false. This may or may not be what you want, depending on your intentions.
Alternately, define a function
array_compare_as_set:and then:
This is subtly different from comparing two
array_sorted values.array_compare_as_setwill eliminate duplicates, makingarray_compare_as_set(ARRAY[1,2,3,3],ARRAY[1,2,3])true, whereasarray_sort(ARRAY[1,2,3,3]) = array_sort(ARRAY[1,2,3])will be false.Both of these approaches will have pretty bad performance. Consider ensuring that you always store your arrays sorted in the first place.