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.
select version();
CREATE TABLE collection (
ID serial NOT NULL PRIMARY KEY,
info jsonb NOT NULL
);
INSERT INTO collection (info)
VALUES
(
'[{"id": "1", "percent": "1"}, {"id": "6", "percent": "2"}]'
),
(
'[{"id": "5", "percent": "3"}, {"id": "1", "percent": "4"}]'
),
(
'[{"id": "1", "percent": "5"}, {"id": "2", "percent": "5"}, {"id": "3", "percent": "5"}]'
);
UPDATE collection
SET info = array_to_json(ARRAY(SELECT jsonb_set(x.original_info,
'{percent}',
(
CASE
WHEN x.original_info ->> 'id' = '1'
THEN '25'
ELSE
concat('"',
x.original_info ->> 'percent',
'"')
END
)::jsonb)
FROM (SELECT jsonb_array_elements(collection.info) original_info) x))::jsonb;
https://dbfiddle.uk/?rdbms=postgres_13&fiddle=a521fee551f2cdf8b189ef0c0191b730