I've created the following table:
CREATE TABLE t1(
a INT UNIQUE,
b varchar(100) NOT NULL,
c INT,
d INT DEFAULT 0,
PRIMARY KEY (a,b));
On a single row this SQL statement works great (the SQL is generated in code):
INSERT INTO t1 (a, b, c, d)
VALUES($params.1, '${params.2}', $params.3, params.4)
ON CONFLICT (a,b) DO
UPDATE SET d=params.4
Is it possible to upsert multiple rows at once? For each update the value of params.4
is different.
var sqlStr = 'INSERT INTO t1 (a, b, c, d) VALUES '
for(let i =0 i < params.length; i++){
sqlStr += `(${params[i].1}, '${params[i].2}', ${params[i].3}, ${params[i].4}),`
}
sqlStr = sqlStr.substring(0, sqlStr .length - 2) +')';
sqlStr += 'ON CONFLICT (a,b) DO UPDATE SET **d=???**' <-- this is the problem
params[i].4
has different value for each row and the ON CONFLICT
statement appears only once (not per row) and SET
doesn't support a WHERE
.
Example, if my table has the following rows:
a | b | c | d
---+---+---+---
1 | 1 | 1 | 1
2 | 2 | 2 | 2
And my new input is [(1,'1',1,11),(2,'2',2,22),(3,'3',3,3)]
.
There are two conflicts - (1,1)
and (2,2)
. The result should be:
a | b | c | d
---+---+---+---
1 | 1 | 1 | 11
2 | 2 | 2 | 22
3 | 3 | 3 | 3