Post

How to update multiple rows with different values with a single PostgreSQL query

2025-03-20

This is arcane and useful knowledge, so you should be grateful I'm giving it to you:

UPDATE my_table
    SET foo = my_table.foo + new_table.foo
    FROM (VALUES (1, 5), (2,6), (3,7)) AS new_table(id, foo)
    WHERE my_table.id = new_table.id;

This works optimally (in terms of duration per row updated) for a specific number of rows per SQL query, and slower as you move away from that number.

Comments

-- No one has left a comment --
Write your comment: