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
7urkm3n
  • 6,054
  • 4
  • 29
  • 46

1 Answers1

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
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786