4

Trying to query for values in a table, where two arrays have the same value, but not necessarily in the same order.

given: a column with a value of

{'first', 'second'}

expected:

SELECT * FROM my_table WHERE array_column = {'second', 'first'}

expected:

SELECT * FROM my_table WHERE array_column = {'second'}

result 1

{'first', 'second'}

result 2: nothing

I can sort the input array I am querying with, but I cannot guarantee that the database will have those arrays stored in that same order. Is there an easy way to do this?

3
  • 1
    Quote from the manual "Arrays are not sets; searching for specific array elements can be a sign of database misdesign." Commented Jun 11, 2018 at 15:41
  • 2
    You are probably looking for the overlaps operator &&: postgresql.org/docs/current/static/functions-array.html Commented Jun 11, 2018 at 15:41
  • @a_horse_with_no_name I was thinking about just using the overlap operator, and then doing exact comparison in code but I wasn't sure if Postgres offers a way to do this through a query. Commented Jun 11, 2018 at 15:43

2 Answers 2

7

Assuming the following data structure:

CREATE TABLE my_table
(
  id BIGINT PRIMARY KEY,
  array_column TEXT[]
);

INSERT INTO my_table ( id, array_column ) VALUES ( 1, ARRAY['first'] );
INSERT INTO my_table ( id, array_column ) VALUES ( 2, ARRAY['first','second'] );
INSERT INTO my_table ( id, array_column ) VALUES ( 3, ARRAY['first','second','third'] );

Combining the contains operator (@>) and the is contained by operator (<@):

SELECT
  *
FROM
  my_table
WHERE
  array_column <@ ARRAY['second','first'] AND
  array_column @> ARRAY['second','first'];

Output:

| id | array_column |
|----|--------------|
|  2 | first,second |

SQLFiddle

Sign up to request clarification or add additional context in comments.

Comments

1

One method is to use the "contains" operators:

SELECT t.*
FROM my_table t
WHERE array_column <@ array('second', 'first') and
      array_column @> array('second', 'first')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.