1

I am trying to figure out in PostgreSQL 11 JSONB query

SELECT id, my_json_field #>> '{field_depth_1, field_depth_2}' 
FROM my_data 
WHERE my_json_field @> '{"other_field": 3}'::jsonb

If other_field is a key-value pair, this works perfectly and I get every row with other_field = 3. However, if other_field is a list of values, eg: [2,3,6,8,10], and I want to find out for every row whether the value 3 exists in the list represented by other_field, how should I write the query?

1 Answer 1

1

Use the operator @>. Per the documentation:

@> jsonb Does the left JSON value contain the right JSON path/value entries at the top level?

Example:

with my_data(id, my_json_field) as (
values
    (1, '{"field_depth_1": {"field_depth_2": "something 1"}, "other_field": 3}'::jsonb),
    (2, '{"field_depth_1": {"field_depth_2": "something 2"}, "other_field": 4}'),
    (3, '{"field_depth_1": {"field_depth_2": "something 3"}, "other_field": [2,3,6,8,10]}'),
    (4, '{"field_depth_1": {"field_depth_2": "something 4"}, "other_field": [2,4,6,8,10]}')
)

select id, my_json_field #>> '{field_depth_1, field_depth_2}' as value
from my_data 
where my_json_field->'other_field' @> '3'

 id |    value    
----+-------------
  1 | something 1
  3 | something 3
(2 rows)    
Sign up to request clarification or add additional context in comments.

Comments

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.