Computer >> Computer tutorials >  >> Programming >> MySQL

Reset AUTO_INCREMENT in MySQL


Truncate the table to reset AUTO_INCREMENT −

truncate table yourTableName;

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

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

Following is the query to reset AUTO_INCREMENT −

mysql> truncate table DemoTable;
Query OK, 0 rows affected (0.80 sec)

Let us insert some records once again. It will by default begin from 1 for AUTO_INCREMENT:

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.09 sec)

Display all records from the table −

mysql> select *from DemoTable;

Output

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