- 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
How can I set my auto-increment value to begin from 1 in MySQL?
You can truncate the table to set auto_increment value to start from 1 in MySQL. Let us first create a table −
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY ); Query OK, 0 rows affected (1.44 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable values(); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable values(); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(); Query OK, 1 row affected (0.06 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+ | StudentId | +-----------+ | 1 | | 2 | | 3 | | 4 | +-----------+ 4 rows in set (0.00 sec)
Now, if you will insert more values, then the StudentId, which is AUTO_INCREMENT will continue from 5. To avoid this, first, truncate the table −
Following is the query to truncate the table to start auto_increment value from 1 −
mysql> truncate table DemoTable; Query OK, 0 rows affected (0.93 sec) mysql> select *from DemoTable; Empty set (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(); Query OK, 1 row affected (0.07 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output. Now, since we truncated the table above, therefore the AUTO_INCREMENT begins from 1 again as shown in the below output −
+-----------+ | StudentId | +-----------+ | 1 | | 2 | | 3 | +-----------+ 3 rows in set (0.00 sec)
To Continue Learning Please Login
Login with Google