Increase unique value in few row [duplicate]

Increase unique value in few row [duplicate]



This question already has an answer here:



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:


update public.test set val=val+1 where val > 5



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



How i can do this?



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






What exception?

– jarlh
Sep 18 '18 at 12:20






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

– darkhac
Sep 18 '18 at 12:29





3 Answers
3



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.


initially deferred



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



Option without deferrable initially immediate


deferrable initially immediate


update test t1
set val=t2.val+1
from (select val from test order by val desc) t2
where t2.val > 5 and t1.val=t2.val



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



Online example with checking that sorting is saved: http://rextester.com/FAU54991



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;

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế