1

I have a column 'carInfo' of type jsonbin my PostgreSQL database and I want to be able to query against multiple values. I want the query to return only those rows that match all criteria. For example, if I had multiple columns, I would write the query like this:

select * 
from car 
where name = 'BMW' 
AND 'year' = 2020

Since my column is of type jsonb I can make use of the containment operator (@>) like this:

select * 
from car 
where carInfo @> cast('{"name":"BMW"}') as jsonb 
  AND carInfo @> cast('{"year":"2020"}')

but I want the query to be dynamic, so that the user can query by any attributes they want.

So, they will send a list of search terms (in this case, the elements of that list would be {"name":"BMW"} and {"year":"2020"}.

Assuming, that I have the list as above, how would the query look like if I wanted to achieve the same result as when using the AND operator?

I tried it like this:

select * 
from car 
where carInfo @> any(array['{"name":"BMW"}', '{"year":"2020"}']::jsonb[])

but it acts the same way as when using the OR operator. I need to find those rows that contain BOTH the search terms

1
  • 2
    You could merge all those key/values into a single jsonb value and see if carInfo contains that, eg SELECT * FROM car WHERE carInfo @> '{"name": "BMW", "year": 2020}'. Your @> any(...) solution could be changed to @> all(...) to make it an AND, but I would highly recommend doing the single @> operation instead if you can. Commented Jul 17, 2020 at 15:45

1 Answer 1

4

You could use @> ALL, but this should be better:

WHERE carInfo @> cast('{"name":"BMW", "year": "2020"}' as jsonb)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. For me this worked only when as jsonb is inside cast function
@KiraAG Unsurprising, since my answer contains a typo. I have fixed it, thanks for the hint.

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.