Skip to content
Advertisement

Update partial jsonb field in Postgres 13

can anyone help please optimize SQL request Postgres 13 (jsonb).

Need to update the “percent” values inside the Jsonb field with the specified ID

This example is working, but it works for a very long time on a large database.

https://dbfiddle.uk/?rdbms=postgres_13&fiddle=a521fee551f2cdf8b189ef0c0191b730

Advertisement

Answer

I would phrase this as:

The logic is quite the same as in your original code, but this skips a few unnecessary casts, and uses direct json array aggregation rather than the intermediate array conversion. Also, I used json operators rather than jsonb_set().

Another important point is that this preserves the ordering of objects in the original json array – while your original code does not.

If there are a lot of rows in the table where no object have the id you search for, then we could pre-filter the data to update only the relevant rows. For this, you can proceed as follows:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement