I want to update rows in my postgres database if the updated version wouldn't violate the primary key constraint. If it would, I want to leave the row as it is.
Assuming the table has primary keys on col1, col2, col3
, if I run a query like this:
UPDATE table SET (col1, col2) = ('AAA', 'BBB')
WHERE col1='AAB' AND col2='BBA';
The query will fail and I will get a duplicate key error if there exists two entries:
'AAA', 'BBB', 'CCC'
'AAB', 'BBA', 'CCC'
i.e col3
is the same between an existing row and a row to be updated.
If I was INSERT
ing rows I would use ON CONFLICT DO NOTHING
but I can't find an implementation of this for UPDATE
. Does an equivalent exist?
AFAIK, there is no such equivalent.
Let us say you are developing an application that connects to a postgresql database, there are a few things you need to keep in mind, in the context of your question:
on conflict
(update or nothing) so it makes sense to have a syntax to let you decide.ON CONFLICT ...
for inserts is not intended to update the primary key fields. The very opposite in fact: it is intended to update all the fields except the ones from the primary key in a single record.While I am on that point, please note that there was no need for a conflict on primary key for the query to fail
1 record with the "convenient" ON UPDATE NO ACTION
foreign key would have made it fail too (which is still better than updating 10M+ records in 50 tables with a ON UPDATE CASCADE
...). BTW, did you know Oracle does not even have the ON UPDATE CASCADE
clause? What do you think is the reason for that?
What can you/should not do in that situation?
UNIQUE
constraints but please please please, NEVER update primary keys.CHECK
or EXCLUSION
), will you really type the additional code it takes with no error in order to, once again, only avoid an error code?current transaction is aborted, commands ignored until end of transaction block
for everything.Here you go:
BEGIN;
SAVEPOINT MySavepoint;
UPDATE mytable set myuniquefield = 3; /*2+ records are going to be updated */
rollback to savepoint MySavepoint;
/*Insert Some more queries here*/
COMMIT;