If you truncate, delete, or remove your database table data. And you want to reset the auto-increment key of your MySQL database table. So, in this tutorial, you will learn how to reset auto increment in MYSQL database.
There may be situations where you need to reset the auto-increment value in MySQL. There are a few reasons to reset the auto-increment in MySQL:
- When you are testing your database and need to start over with a new set of data.
- When you delete a significant number of records from a table and want to reuse the auto-increment value.
- When you want to change the initial auto-increment value to a specific number.
How To Reset Auto increment in MySQL
By using these steps, you can reset auto-increment in MySQL:
- Step 1: Connect to MySQL server
- Step 2: Select the database
- Step 3: Reset the auto-increment value
- Step 4: Verify the auto-increment value
Step 1: Connect to MySQL server
Firstly, open your terminal or command line and execute the following command into it to connect mysql server:
mysql -u username -p
Replace “username” with your MySQL username and press enter. You will be prompted to enter the MySQL password.
When you enter the password and press enter, you will be connected to the MySQL server.
Step 2: Select the database
Once you have logged in, you need to execute the following command on MySQL to select the database in which the table is located:
USE database_name;
Replace “database_name” with the name of the database in which the table resides.
Step 3: Reset the auto-increment value
To reset the auto-increment value (id) in MySQL, you need to execute the ALTER TABLE command on MySQL:
ALTER TABLE table_name AUTO_INCREMENT = value;
To replace “table_name” with the name of the table whose auto-increment value you want to reset, and “value” with the new auto-increment value.
For example, if you want to reset the auto-increment ID of the “users” table to 1, you can use the following command:
ALTER TABLE users AUTO_INCREMENT = 1;
Step 4: Verify the auto-increment value
To verify that the auto-increment value has been reset, you can use the SHOW CREATE TABLE command. This command displays the structure of the table, including the auto-increment value. You can use the following command:
SHOW CREATE TABLE table_name;
Replace “table_name” with the name of the table you want to check.
Conclusion
Resetting auto-increment in MySQL is a straightforward process that can be done using the ALTER TABLE command. Whether you are testing your database, deleting records, or changing the starting auto-increment value, resetting the auto-increment value in MySQL can be a useful tool. By following the steps mentioned in this article, you can easily reset the auto-increment value in MySQL and ensure that your database is running efficiently.