MySQL - How can I fix an auto increment field with deleted rows from 1,2,3,4,5 to 1,3,5). Now we want it to be 1,2,3


Let us first create a table −

mysql> create table DemoTable1955
   (
   UserId int NOT NULL AUTO_INCREMENT
   ,
   PRIMARY KEY(UserId)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1955 values();
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1955 values();
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1955 values();
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1955 values();
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1955 values();
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1955;

This will produce the following output −

+--------+
| UserId |
+--------+
|      1 |
|      2 |
|      3 |
|      4 |
|      5 |
+--------+
5 rows in set (0.00 sec)

Here is the query to delete rows from table −

mysql> delete from DemoTable1955 where UserId  IN(2,4);
Query OK, 2 rows affected (0.00 sec)

Now check the table records −

mysql> select * from DemoTable1955;

This will produce the following output −

+--------+
| UserId |
+--------+
|      1 |
|      3 |
|      5 |
+--------+
3 rows in set (0.00 sec)

Here is the query to fix an auto-increment field that has deleted rows (1,2,3,4,5 to 1,3,5). Below query will make the column to begin from 1 to be like 1,2,3 −

mysql> update DemoTable1955
   set UserId = (@increment_value := @increment_value+ 1)
   order by UserId;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 3  Changed: 2 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1955;

This will produce the following output −

+--------+
| UserId |
+--------+
|      1 |
|      2 |
|      3 |
+--------+
3 rows in set (0.00 sec)

Updated on: 31-Dec-2019

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements