Filter array attribute in jsonb column type using jsonb_array_elements_text
-
18-02-2021 - |
Question
My Postgres version: 10.9
Using JsonB Column type which has a below structure:
columnName: favorites
{
"favouriteCity": "Boston",
"favoriteColors": ["Blue", "Red", "Green"],
}
Now, I want to filter all records which have favorite colors as Blue assigned.
I tried the below queries, but it didn't work.
select *
from r_fav
where favorites->>'favoriteColors' in ('Blue', 'Red')
or
jsonb_array_elements_text(favorites->>'favoriteColors' @>'Blue', 'Red')
Any idea how can I filter this?
Solution
You can use the contains all ?&
operator with arrays:
select *
from r_fav
where favorites -> 'favoriteColors' ?| array['Blue', 'Red']
That will return rows at least one of the colors exist in the array. If want those where all colors are contained, use the operator ?&
instead
OTHER TIPS
Use an array of values, bear in mind both values must be included in favoriteColors
select
favourites->'favouriteCity'
from
t
where
favourites->'favoriteColors' @> '["Blue","Red"]'::jsonb;
| ?column? | | :------- | | "Boston" |
Let me add this comment of jjanes:
You could also put the key name on the other side of the @> operator. select favourites->'favouriteCity' from t where favourites @> '{"favoriteColors":["Blue","Red"]}'::jsonb; The two ways of formulating it will benefit from different indexes, so it may be worthwhile to try both
db<>fiddle here