6

I have a table with a jsonb data column, which looks like this:

data: {
    "categories": [
        "Category A",
        "Category D"
    ],
    "something": "dsa",
}

I would like to query rows that have one or more strings existing inside categories array (not empty intersection).

Let's suppose these strings to check against are "Category A" and "Category B".

How would such query look like?

Here's a query that does similar thing except it checks for all supplied strings to be existing in categories array:

SELECT *
FROM table
WHERE data->'categories' @> '["Category A", "Category B"]'

I need this query to match at least one string, not all.

1
  • Which version of PG? There are major differences for json types between 9.3 and 9.4. Commented Sep 28, 2015 at 0:42

1 Answer 1

19

There is a ?| operator taking jsonb and text[] described as exists any:

select '["Category A", "Category D"]'::jsonb ?| array['Category A', 'Category B'];
 ?column? 
----------
 t

select '["Category A", "Category D"]'::jsonb ?| array['Category Ax', 'Category B'];
 ?column? 
----------
 f
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.