I have a fairly simple table in PostgreSQL database (v 9.6):
CREATE TABLE foobar (id serial, data jsonb);
Here is an example of JSONB document that is stored in data column:
[{ key: 'foo', value: 100 }, { key: 'bar', value: 5 }, { key: 'baz', value: 10 }]
I am trying to write a select that will return every row where conditions in JSONB document are met and select only specified nested documents; i.e. for every row where foo
is greater than X
return all nested documents that have baz
as key.
So far I've came with a query like this but it does not work — it is returning 0 records.
SELECT id
FROM foobar
WHERE (data->>'key' = 'foo' AND (data->>'value')::numeric > 5)
OR (data->>'key' = 'bar' AND (data->>'value')::numeric < 10)
Also it would be great if anyone knows how to optimize the final query. Thanks!
>=
and<=
? – user933161