Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a primary key without triggering unique key violation

Tags:

sql

sqlite

I just came to this very simple situation where I needed to shift a primary key up a certain value. Suppose the following table:

CREATE TABLE Test (
 Id INTEGER PRIMARY KEY,
 Desc TEXT);

Loaded with the following values:

INSERT INTO Test VALUES (0,'one');
INSERT INTO Test VALUES (1,'two');

If there's an attempt at updating the primary key, it will, of course, fail:

UPDATE Test SET Id = Id+1;

Error: column id is not unique

Is there some way to suspend unicity check until after the update query has run?

like image 369
MPelletier Avatar asked Mar 04 '26 21:03

MPelletier


2 Answers

Find a nice pivot point, and move the data around that pivot. For example, if all your IDs are positive, a good pivot is 0.

When you would normally do

UPDATE Test SET Id = Id+1;

Do this sequence instead

UPDATE Test SET Id = -Id;
UPDATE Test SET Id = -Id +1;

For times, you can find a similar pivot point, but the formula is just a tad harder.

like image 154
RichardTheKiwi Avatar answered Mar 06 '26 13:03

RichardTheKiwi


without understanding the fundamental problem (and yeah, you seem like a victim of code and run on this one!), multiplying the ID by the largest value in the table should work.

update test
set id = id * (select max(id) + 1 from test)

However, it's dirty, and really, databases make it hard to change primary keys for a reason...

like image 42
Neville Kuyt Avatar answered Mar 06 '26 13:03

Neville Kuyt



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!