- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements