I have a jsonb
column called chores
in my work
table with data looking something like this:
[{"task": "feed_dog", "value": "Daily"},{"task": "mop_floor", "value": "Weekly"]
There could be zero to dozens of tasks in the chores
array for each user.
How can I query by task name? For example, pull all records where at least one task
is feed_dog
.
SELECT chores->>'task' FROM work
returns a bunch of null
results, as does SELECT chores->'task' FROM work
.
Advertisement
Answer
You need to unnest the array:
select w.* from "work" w where exists (select * from jsonb_array_elements(w.chores) as t(task) where t.task ->> 'task" = 'feed_dog');
With Postgres 12 this is a bit easier to write:
select * from "work" w where jsonb_path_exists(w.chores, '$[*] ? (@.task == "feed_dog")')