Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use jsonb_set with the new value (3rd argument) coming from a select statement?

I have a table with a jsonb column and I want to migrate every record to a new schema.

Old schema: {"foo": "bar"}
New schema: {"foo": {"value": "bar"}

The bar value varies by row and I want to preserve that value. I need some way to lookup the value of foo from each record.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

WITH data AS (
  SELECT id AS id, col -> 'foo' AS foo
  FROM t
) UPDATE t SET col = jsonb_set('{"foo": {"value": ""}}', '{foo,value}', SELECT foo FROM data WHERE data.id = t.id);

I get this error with Postgres 11.21.

ERROR:  syntax error at or near "SELECT"
LINE 4: ...jsonb_set('{"foo": {"value": ""}', '{foo,value}', SELECT foo...

>Solution :

No need for a CTE, and you can move the current content without a subquery:

UPDATE t 
SET col = jsonb_set(col, '{foo}', jsonb_build_object('value', col->>'foo'))
WHERE id = ?; -- if needed
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading