A self explaining test:
> create table ainc(id int auto_increment primary key);
Query OK, 0 rows affected (0.14 sec)
> insert into ainc values (null), (null), (null), (null);
Query OK, 4 rows affected (0.04 sec)
Records: 4 Duplicates: 0 Warnings: 0
> select * from ainc;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
+----+
4 rows in set (0.01 sec)
> update ainc set id = id + 1 where id > 2;
ERROR 1062 (23000): Duplicate entry '4' for key 'PRIMARY'
> update ainc set id = id + 1 where id > 2 order by id desc;
Query OK, 2 rows affected (0.04 sec)
Rows matched: 2 Changed: 2 Warnings: 0
> select * from ainc;
+----+
| id |
+----+
| 1 |
| 2 |
| 4 |
| 5 |
+----+
Summary: Just make use of the supported order by
in the update statement.
Then don't forget to adjust your auto_increment value with
ALTER TABLE ainc AUTO_INCREMENT = 5;
or you will get this:
> insert into ainc values (null);
ERROR 1062 (23000): Duplicate entry '5' for key 'PRIMARY'
> ALTER TABLE ainc AUTO_INCREMENT = 5;
Query OK, 4 rows affected (0.52 sec)
Records: 4 Duplicates: 0 Warnings: 0
> insert into ainc values (null);
Query OK, 1 row affected (0.01 sec)
> select * from ainc;
+----+
| id |
+----+
| 1 |
| 2 |
| 4 |
| 5 |
| 6 |
+----+