Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Update primary key, avoid conflict

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"

like image 727
Erich Kitzmueller Avatar asked Nov 16 '25 05:11

Erich Kitzmueller


1 Answers

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
like image 128
Vao Tsun Avatar answered Nov 17 '25 19:11

Vao Tsun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!