2

I want to do a batch update in PostgreSQL in one go by passing in an array of JSON objects, but I am not sure how I should approach the problem.

An example:

[
  { "oldId": 25, "newId": 30 },
  { "oldId": 41, "newId": 53 }
]

should resolve as: UPDATE table SET id = 30 WHERE id = 25 and UPDATE table SET id = 41 WHERE id = 53, in a single command, of course.

2
  • There is no table (definition) in your question. Only something that looks like json. and some text. Commented Jan 21, 2022 at 13:16
  • I am not sure how this question is schema specific Commented Jan 21, 2022 at 13:58

2 Answers 2

3

Use the function jsonb_array_elements() in the from clause:

update my_table
set id = (elem->'newId')::int
from jsonb_array_elements(
    '[
      { "oldId": 25, "newId": 30 },
      { "oldId": 41, "newId": 50 }
    ]') as elem
where id = (elem->'oldId')::int

Note that if the column id is unique (primary key) the update may result in a duplication error depending on the data provided.

Db<>fiddle.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to unnest the array the cast the elements to the proper data type:

update the_table
   set id = (x.item ->> 'newId')::int
from jsonb_array_elements('[...]') x(item)
where the_table.id = (x.item ->> 'oldId')::int

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.