How to reset the primary key of a table in mysql?


The reset the primary key of a table means to reset the auto_increment property to 1. The syntax is as follows to reset the primary key of a table.

alter table yourTableName auto_increment = 1;

To understand, let us create a table −

mysql> create table ResetPrimaryKey
−> (
   −> Id int auto_increment,
   −> PRIMARY KEY(Id)
−> );
Query OK, 0 rows affected (0.59 sec)

Insert some records into the table. The query to insert records is as follows −

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.18 sec)

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.15 sec)

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

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

Now you can display all records with the help of select statement. The query is as follows −

mysql> select *from ResetPrimaryKey;

The following is the output that displays only the ID, which is a Primary Key:

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

Here is the query to reset the primary key of a table using alter −

mysql> alter table ResetPrimaryKey auto_increment = 1;
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0

The query to check that we have added auto_increment property successfully or not:

mysql> desc ResetPrimaryKey;

The following is the output −

+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| Id    | int(11) | NO   | PRI | NULL    | auto_increment |
+-------+---------+------+-----+---------+----------------+
1 row in set (0.11 sec)

Updated on: 29-Jun-2020

796 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements