- 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
Reset Primary Key in MySQL
To reset primary key, at first use TRUNCATE table, then use ALTER TABLE. Let us first create a table −
mysql> create table DemoTable1929 ( 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 DemoTable1929 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1929 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1929 values(); Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1929;
This will produce the following output −
+--------+ | UserId | +--------+ | 1 | | 2 | | 3 | +--------+ 3 rows in set (0.00 sec)
Here is the query to reset primary key −
mysql> truncate table DemoTable1929; Query OK, 0 rows affected (0.00 sec) mysql> alter table DemoTable1929 auto_increment=1; Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0
Now you can insert record, it will reset the primary key value from 1 −
mysql> insert into DemoTable1929 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1929 values(); Query OK, 1 row affected (0.00 sec)
Display all records from table using select statement −
mysql> select * from DemoTable1929;
This will produce the following output −
+--------+ | UserId | +--------+ | 1 | | 2 | +--------+ 2 rows in set (0.00 sec)
Advertisements