I would like to use the insert.. on confict do update.. syntax with a table that has unique constraints on two columns. Is this possible?
e.g. mytable has separate unique constraints on col1 and col2.
I can write:
INSERT INTO mytable(col1, col2, col3) values ('A', 'B', 0) ON CONFLICT DO NOTHING;
However this doesn't work:
INSERT INTO mytable(col1, col2, col3) VALUES ('A', 'B', 0)
ON CONFLICT
DO UPDATE SET col3 = EXCLUDED.col3 + 1;
ERROR: ON CONFLICT DO UPDATE requires inference specification or constraint name
This also doesn't work:
INSERT INTO mytable(col1, col2, col3) VALUES ('A', 'B', 0)
ON CONFLICT (col1, col2)
DO UPDATE SET col3 = EXCLUDED.col3 + 1;
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
This syntax seems to be designed for a single composite unique constraint over two columns, rather than two constraints.
Is there any way to do a conditional update if either unique constraint is violated? This question How to upsert in Postgres on conflict on one of 2 columns? alludes to it but doesn't provide the syntax.
simple case on conflict
: the key is kept, and (some of) the dependent fields are updated. In your case, you intend to update another (candidate) key. In fact, you attempt to update both (candidate) keys, which is beyond my logic. – wildplasserUNIQUE (col1, col2)
will probably do what you want. (it is logically redundant, but the data model makes little or no sense anyway) – wildplasser