Compare arrays for equality, ignoring order of elements
You can use contained by operator:
(array1 <@ array2 and array1 @> array2)
The additional module intarray provides operators for arrays of integer
, which are typically (much) faster. Install once per database with (in Postgres 9.1 or later):
CREATE EXTENSION intarray;
Then you can:
SELECT uniq(sort(ids)) = uniq(sort(signed_ids));
Or:
SELECT ids @> signed_ids AND ids <@ signed_ids;
Bold emphasis on functions and operators from intarray.
In the second example, operator resolution arrives at the specialized intarray operators if left and right argument are type integer[]
.
Both expressions will ignore order and duplicity of elements. Further reading in the helpful manual here.
intarray
operators only work for arrays of integer
(int4
), not bigint
(int8
) or smallint
(int2
) or any other data type.
Unlike the default generic operators, intarray
operators do not accept NULL values in arrays. NULL in any involved array raises an exception. If you need to work with NULL values, you can default to the standard, generic operators by schema-qualifying the operator with the OPERATOR
construct:
SELECT ARRAY[1,4,null,3]::int[] OPERATOR(pg_catalog.@>) ARRAY[3,1]::int[]
The generic operators can't use indexes with an intarray
operator class and vice versa.
Related:
- GIN index on smallint[] column not used or error "operator is not unique"