Increase unique value in few row

Viewed 111

I have the table create as

create table public.test
(
    val int unique not null
)

This table contains some rows

|   Val  |
|--------|
|1       |
|2       |
|3       |
|4       |
|5       |
|6       |
|7       |
|8       |
|9       |

I wanna increment all values greater then 5 (using PostgreSQL). But if try update public.test set val=val+1 where val > 5 i will get exception:

ERROR: duplicate key value violates unique constraint "test_val_key" DETAIL: Key (val)=(7) already exists.

How i can do this?

3 Answers

If you need that on regular basis you should create the constraint as deferrable:

create table test
(
    val int not null
);
alter table test
   add constraint unique_value unique(val)
   deferrable initially immediate;

For the intended update to work, it's not necessary to mark the constraint as initially deferred or to change the constraints to deferrable in the session.

With the above constraint the following update works just fine:

update test set val=val+1 where val > 5;

Online example: http://rextester.com/KXI21597

One option is to drop the unique constraint and then add it back.

Another option is a hack:

update public.test
    set val = - val
    where val > 5;

update public.test
    set val = (- val) + 1
    where val < 0;
Related