MySQL Update – How to Swap ID Between Two Rows

MySQLupdate

We have existing table:


| id |    name    |   color   | calories |
------------------------------------------
| 1  | apple      | red       | 20       |
| 2  | orange     | orange    | 10       |
| 3  | grapes     | green     | 5        |
| 4  | bananas    | yellow    | 15       |
| 5  | plum       | purple    | 25       |
------------------------------------------

Column id is unique and primary key. I'm facing a problem with edit/update records when, i heed to change for example in row 3 where, id = 3 to id = 5 and row 5 where, id = 5 to id = 3… Like swap id between rows 3 and 5. Of course there are duplicate, but how to resolve this scenario…

But MySQL logically throws out the error.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '5' for key 'PRIMARY'

I know it is stupid scenario, but we have a customer who wants it that way. He want to edit/update each existing records.

Best Answer

These should be wrapped in a transaction using an intermediate value;

begin;
set @from = 3;
set @to = 5;
set @tmpid = (2000000 + @from % 147483647);
update col set id=@tmpid where id = @from;
update col set id=@from where id=@to;
update col set id=@to where id = @tmpid;
commit;

Choosing a high end @tmpid namespace to avoid collisions is important not to run into trouble later.