0

How to batch update the following sample more efficiently.

users = [{id: 424, pos: 1}, {id: 23, pos: 2}, {id: 55, pos: 3}, ...]

//currently loop updating each {i}:
   UPDATE users SET position = i.pos WHERE id = i.id
2
  • 1
    Aren't you looking for this ? stackoverflow.com/a/20224370/3277024 Commented Feb 6, 2020 at 18:02
  • @JMG Yes, i take a look. Thx Commented Feb 6, 2020 at 18:08

1 Answer 1

1

You can use unnest():

update users u
    set position = user.pos 
    from (values ([{id: 424, pos: 1}, {id: 23, pos: 2}, {id: 55, pos: 3}, ...])
         ) v(users) cross join lateral
         unnest(users) user
    where u.id = user.id
Sign up to request clarification or add additional context in comments.

3 Comments

This is supposed to help me, let me try
Could you explain me this v(users) cross join lateral unnest(users) user, if my array is named list = [] for example ? I am kinda getting syntax issue here.

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.