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)