I have table in postgresql with fields id
(unique) and val
.
I want to execute something like this:
INSERT INTO my_table (id, val)
VALUES (%(id)s, %(val)s)
ON CONFLICT(id) DO UPDATE
SET val = val + %(val)s
Data to insert is like [{"id": 123, "val": 5}, {"id": 456, "val": 8}, ...]
. Is there any way to upsert all of these with one query?
cursor.executemany
won't do, it's the same as to make queries with all of these dicts in a loop one after another.
Without ON CONFLICT DO UPDATE I could just do something like "insert into mytable (id, val) values " + ', '.join(['(%s, %s)'] * len(data))
and transform data to the list [id1, val1, id2, val2, ...]. But I've no idea how to combine multiple values to insert and update statement.