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
jsonbvalue and see ifcarInfocontains that, egSELECT * FROM car WHERE carInfo @> '{"name": "BMW", "year": 2020}'. Your@> any(...)solution could be changed to@> all(...)to make it anAND, but I would highly recommend doing the single@>operation instead if you can.