I want to update the primary key in several rows of a table. If all rows were updated, the key would be unique again, but the update of the first row results in a temporary conflict with the key of the second row. Is there an elegant way to solve this?
Example:
create table erichtest ( i integer, v varchar(200) );
alter table erichtest add constraint pk_erichtest primary key(i);
insert into erichtest values(1, 'Eins');
insert into erichtest values(2, 'Zwei');
update erichtest set i=i+1;
ERROR: duplicate key value violates unique constraint "pk_erichtest"
Something like this should help:
b=# begin;
BEGIN
b=# alter table erichtest drop constraint pk_erichtest ;
ALTER TABLE
b=# alter table erichtest add constraint pk_erichtest primary key (i) DEFERRABLE INITIALLY IMMEDIATE;
ALTER TABLE
b=# set constraints pk_erichtest deferred ;
SET CONSTRAINTS
b=# update erichtest set i=i+1;
UPDATE 2
b=# select * from erichtest ;
i | v
---+------
2 | Eins
3 | Zwei
(2 rows)
b=# end;
COMMIT
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With