Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

My products table has a jsonb column called 'specs'.

This specs hash will often have an array field, let's call it 'spec_options'.

When querying this table, I need to find any product that has certain spec options.

Let's say we have a product with these spec_options:

['b', 'c', 'd']

And the user wants to find products with these spec_options:

['a', 'b', 'c']

The query I need should return find above product.

This where clause worked just fine when the field wasn't an array:

'["a", "b", "c"]'::jsonb ? (specs->>'spec_options')

But now that it's an array, I think I need to use the |? operator, and I can't work out how to get the right side of this operation into the correct format. (I think it needs to be text[] but I'm not sure.)

share|improve this question

You can use the @> operator.

From the docs:

@> Does the left JSON value contain within it the right value?

So in your case it would look something like this:

select * from products where specs @> '{"spec_options": ["a", "b", "c"]}';
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.