Postgresql – How to query JSONB field type

postgresql-13

I have a jsonb field named 'queues' it contains the following:

{
  "call_queue_pid": [
    1,
    2,
    3
  ],
  "omni_queue_pid": [
    4,
    5,
    6
  ]
}

I try the below query to search omni_queue_pid = 5

Select * 
from ws a,
    jsonb_array_elements(a.queues::jsonb) j 
Where cast(j->> 'omni_queue_pid' as integer) = 5

but it returns SQL Error [22023]: ERROR: cannot extract elements from an object

what I missed?

need help

thanks
Don

Best Answer

You need to unnest the array:

Select * 
from ws a
  cross join jsonb_array_elements_text(a.queues -> 'omni_queue_pid') as o(id)
Where o.id::int = 5

It's unclear what result you exactly want, but an EXISTS condition might be more efficient:

select * 
from ws a
where exists (select *
              from jsonb_array_elements_text(a.queues -> 'omni_queue_pid') as o(id)
              Where o.id::int = 5)

Or using a jsonpath operator:

select * 
from ws
where queues @? '$.omni_queue_pid[*] == 5'