Using PostgreSQL 14 I have a table ‘fruits’ with a JSONB column named ‘items’ containing this sample data:
[{"anz": 4, "typ": "Banana"}, {"anz": 5, "typ": "Apple"}, {"anz": 2, "typ": "Grapefruit"}]
[{"anz": 1, "typ": "Banana"}, {"anz": 1, "typ": "Apple"}, {"anz": 3, "typ": "Grapefruit"}]
this works:
SELECT * FROM fruits WHERE items @> '[{"typ":"Apple"}]';
SELECT * FROM fruits WHERE (items -> 0 ->> 'lvl')::int > 4;
Bu now I would like to fetch only the record where Apple has ‘anz > 3’. Combining the WHERE clauses from the queries above doesn’t fit of course. What’s the appropriate SQL?
2
Answers
One option is to extract the array into elements by using
json_array_elements()
then apply your conditions:Results :
Demo here
You’re using
jsonb
, so you have the full support ofJSONPath
expressions: demo at db<>fiddle@?
operator checks if thejsonb
returns anything for the jsonpath expression$
is your top-level thing[*]
checks all elements of the array?
is a filter, like awhere
@
is the element considered by the filter&&
is the logicalAND
operator