I have a table with a JSONB row which holds data in this form:
id | data |
---|---|
1 | {"key_1": "value1"} |
2 | {"another_key": "some_value"} |
Given another JSON structure like this {"key_1": ["value1", "value2"]}
, what shall I use to get the first row to match a query?
I had no luck using the JSON operators of PostgreSQL in the doc https://www.postgresql.org/docs/9.5/functions-json.html
2
Answers
id
, then addorder by id limit 1
at the end.@@
predicate check and@?
path exists operators. If you’re looking for a row with a jsonb value resembling the one you showed (key_1
with an array under it): demo@>
object containment operator instead: demoIf you’re looking for rows where there’s
key_1
on the top level, and under it, there’s any of the values in your array, @Serg’s example got it right. In version 14 and above, you can use[key]
subscriptIn earlier versions, you need the
->
accessor:You can use <@ comparison operator