When updating a relational table:
CREATE TABLE foo ( id serial primary key, credit numeric);
UPDATE foo SET bar = bar + $1 WHERE id = $2;
However the equivalent in JSON doesn't work:
CREATE TABLE foo ( id serial primary key, data json);
UPDATE foo SET data->'bar' = data->'bar' + $1 WHERE id = $2;
The error I get is error: syntax error at or near "->"
- which is rather ambiguous.
How do I do this?
I am using postgres 9.3.4
In light of @GordonLinoff's comment below, I have created a feature request: https://postgresql.uservoice.com/forums/21853-general/suggestions/6466818-create-update-delete-on-json-keys
You can vote on it if you would like this feature too.
Based on @joonas.fi's and pozs's answers, I came up with a slightly more 'beautiful' solution
UPDATE foo
SET data = jsonb_set(data, '{bar}', (COALESCE(data->>'bar','0')::int + 1)::text::jsonb)
WHERE id = 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With