0

Given the database table below where tags are arrays stored as JSONB, how can I write an SQL query to only select ids that contain all tags value's in an array?

e.g only records 1 and 2 would be returned for the array {"London", "Sydney"}


 id |             tags                 
----+---------------------------------------------------
  1 | [{"value": "Sydney"..}, {"value": "London"..}, {"value": "Munich"..}]
  2 | [{"value": "Sydney"..}, {"value": "London"..}]
  3 | [{"value": "London"..}]
  4 | [{"value": "Sydney"..}]

I managed to construct this query however it does not return an absolute match for ALL the items in the array which is what I'm after..

SELECT * 
FROM mytable
WHERE EXISTS (
    SELECT TRUE 
    FROM jsonb_array_elements(tags) tag 
    WHERE tag->>'value' IN ('London', 'Sydney')
)
2
  • What if you have a row with [{"value": "Sydney"}, {"value": "London"}, {"value": "Munich"}] should that also be returned? Commented Nov 28, 2022 at 8:04
  • Yes, that can also be returned! just edited the question to clarify. Commented Nov 28, 2022 at 8:07

1 Answer 1

2

You can use the contains operator @> with a JSON array:

select * 
from the_table
where tags @> '[{"value": "London"}, {"value": "Sydney"}]'

Or you can use a JSON path expression

select * 
from the_table
where jsonb_path_query_array(tags, '$[*].value') ?& array['London', 'Sydney']
Sign up to request clarification or add additional context in comments.

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.