[mysql] How to reset AUTO_INCREMENT in MySQL?

How can I reset the AUTO_INCREMENT of a field?
I want it to start counting from 1 again.

This question is related to mysql sql auto-increment

The answer is


The auto increment counter for a table can be (re)set in two ways:

  1. By executing a query, like others already explained:

    ALTER TABLE <table_name> AUTO_INCREMENT=<table_id>;

  2. Using Workbench or other visual database design tool. I am gonna show in Workbench how it is done - but it shouldn't be much different in other tool as well. By right click over the desired table and choosing Alter table from the context menu. On the bottom you can see all the available options for altering a table. Choose Options and you will get this form: enter image description here

    Then just set the desired value in the field Auto increment as shown in the image. This will basically execute the query shown in the first option.


Adding an update because the functionality changed in MySQL 5.6. As of MySQL 5.6 you CAN use the simple ALTER TABLE with InnoDB:

ALTER TABLE tablename AUTO_INCREMENT = 1;

The docs are updated to reflect this:

http://dev.mysql.com/doc/refman/5.6/en/alter-table.html

My testing also shows that the table is NOT copied, the value is simply changed.


You can also use the syntax TRUNCATE table like this : TRUNCATE TABLE table_name

BEWARE!! TRUNCATE TABLE your_table will delete everything in your your_table!!


Simply like this:

ALTER TABLE tablename AUTO_INCREMENT = value;

reference: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html


ALTER TABLE news_feed DROP id

ALTER TABLE news_feed ADD  id BIGINT( 200 ) NOT NULL AUTO_INCREMENT FIRST ,ADD PRIMARY KEY (id)

I used this in some of my scripts , the id field is droped and then added back with previous settings , all the existent fields within the database table are filled in with new auto increment values , this should also work with InnoDB .

Note that all the fields within the table will be recounted and will have other ids !!!.


Here is my solution, but I will not advise to do this if your column has constraints or is connected as foreign key to other tables as it would have bad effects or will not even work.

> First : drop the column

ALTER TABLE tbl_name DROP COLUMN column_id

> Second : recreate the column and set it as FIRST if you want it as the first column I assume.

ALTER TABLE tbl_access ADD COLUMN `access_id` int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT FIRST

This works well!


SET  @num := 0;

UPDATE your_table SET id = @num := (@num+1);

ALTER TABLE your_table AUTO_INCREMENT =1;

I think this will do it


To update latest plus one id

 ALTER TABLE table_name AUTO_INCREMENT = 
 (SELECT (id+1) id FROM table_name order by id desc limit 1);

As of MySQL 5.6 the approach below works faster due to online DDL (note algorithm=inplace):

alter table tablename auto_increment=1, algorithm=inplace;


ALTER TABLE tablename AUTO_INCREMENT = 1


The best solution that worked for me:

ALTER TABLE my_table MODIFY COLUMN ID INT(10) UNSIGNED;
COMMIT;
ALTER TABLE my_table MODIFY COLUMN ID INT(10) UNSIGNED AUTO_INCREMENT;
COMMIT;

Its fast, works with innoDB, and I don't need to know the current maximum value! This way the auto increment counter will reset and it will start automatically from the maximum value exists.


The highest rated answers to this question all recommend "ALTER yourtable AUTO_INCREMENT= value". However, this only works when value in the alter is greater than the current max value of the autoincrement column. According to the MySQL 8 documentation:

You cannot reset the counter to a value less than or equal to the value that is currently in use. For both InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum AUTO_INCREMENT column value plus one.

In essence, you can only alter AUTO_INCREMENT to increase the value of the autoincrement column, not reset it to 1, as the OP asks in the second part of the question. For options that actually allow you set the AUTO_INCREMENT downward from its current max, take a look at Reorder / reset auto increment primary key.


You need to follow the advice from Miles M comment and here is a little code that fixes the range in mysql. Also u need to open up my.ini(Mysql) and change max_execution_time=60 to max_execution_time=6000; for large databases. Dont use "ALTER TABLE tablename AUTO_INCREMENT = 1" it will delete everything in your database.

$con=mysqli_connect($dbhost, $dbuser, $dbpass, $database);
$res=mysqli_query($con, "select * FROM data WHERE id LIKE id ORDER BY id ASC");
$count = 0;  
while ($row = mysqli_fetch_array($res)){
         $count++;
        
    mysqli_query($con, "UPDATE data SET id='".$count."' WHERE id='".$row['id']."'");
    
         }
         echo 'Done reseting id';
         mysqli_close($con);

it is for empty table:

ALTER TABLE `table_name` AUTO_INCREMENT = 1;

if you have data but you want to tidy up it, i recommend use this :

ALTER TABLE `table_name` DROP `auto_colmn`;
ALTER TABLE `table_name` ADD  `auto_colmn` INT( {many you want} ) NOT NULL AUTO_INCREMENT FIRST ,ADD PRIMARY KEY (`auto_colmn`);

I googled and found this question, but the answer I am really looking for fulfils two criteria:

  1. using purely MySQL queries
  2. reset an existing table auto-increment to max(id) + 1

Since I couldn't find exactly what I want here, I have cobbled the answer from various answers and sharing it here.

Few things to note:

  1. the table in question is InnoDB
  2. the table uses the field id with type as int as primary key
  3. the only way to do this purely in MySQL is to use stored procedure
  4. my images below are using SequelPro as the GUI. You should be able to adapt it based on your preferred MySQL editor
  5. I have tested this on MySQL Ver 14.14 Distrib 5.5.61, for debian-linux-gnu

Step 1: Create Stored Procedure

create a stored procedure like this:

DELIMITER //
CREATE PROCEDURE reset_autoincrement(IN tablename varchar(200))
BEGIN

      SET @get_next_inc = CONCAT('SELECT @next_inc := max(id) + 1 FROM ',tablename,';');
      PREPARE stmt FROM @get_next_inc; 
      EXECUTE stmt; 
      SELECT @next_inc AS result;
      DEALLOCATE PREPARE stmt; 

      set @alter_statement = concat('ALTER TABLE ', tablename, ' AUTO_INCREMENT = ', @next_inc, ';');
      PREPARE stmt FROM @alter_statement;
      EXECUTE stmt;
      DEALLOCATE PREPARE stmt;
END //
DELIMITER ;

Then run it.

Before run, it looks like this when you look under Stored Procedures in your database.

enter image description here

When I run, I simply select the stored procedure and press Run Selection

enter image description here

Note: the delimiters part are crucial. Hence if you copy and paste from the top selected answers in this question, they tend not to work for this reason.

After I run, I should see the stored procedure

enter image description here

If you need to change the stored procedure, you need to delete the stored procedure, then select to run again.

Step 2: Call the stored procedure

This time you can simply use normal MySQL queries.

call reset_autoincrement('products');

Originally from my own SQL queries notes in https://simkimsia.com/library/sql-queries/#mysql-reset-autoinc and adapted for StackOverflow


There are good options given in How To Reset MySQL Autoincrement Column

Note that ALTER TABLE tablename AUTO_INCREMENT = value; does not work for InnoDB


I suggest you to go to Query Browser and do the following:

  1. Go to schemata and find the table you want to alter.

  2. Right click and select copy create statement.

  3. Open a result tab and paste the create statement their.

  4. Go to the last line of the create statement and look for the Auto_Increment=N, (Where N is a current number for auto_increment field.)

  5. Replace N with 1.

  6. Press ctrl+enter.

Auto_increment should reset to one once you enter new row int the table.

I don't know what will happen if you try to add a row where an auto_increment field value already exist.


Best way is remove the field with AI and add it again with AI, works for all tables


I tried to alter the table and set auto_increment to 1 but it did not work. I resolved to delete the column name I was incrementing, then create a new column with your preferred name and set that new column to increment from the onset.


SET @num := 0;
UPDATE your_table SET id = @num := (@num+1);
ALTER TABLE your_table AUTO_INCREMENT =1;

You can simply truncate the table to reset the sequence

TRUNCATE TABLE TABLE_NAME

enter image description hereThere is a very easy way with phpmyadmin under the "operations" tab, you can set, in the table options, autoincrement to the number you want.


Try Run This Query

 ALTER TABLE tablename AUTO_INCREMENT = value;

Or Try This Query For The Reset Auto Increment

 ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL;

And Set Auto Increment Then Run This Query

  ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to auto-increment

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME? How to make MySQL table primary key auto increment with some prefix Get the new record primary key ID from MySQL insert query? How to generate auto increment field in select query Get current AUTO_INCREMENT value for any table Add Auto-Increment ID to existing table? How to AUTO_INCREMENT in db2? How to create id with AUTO_INCREMENT on Oracle? auto increment ID in H2 database ERROR: permission denied for sequence cities_id_seq using Postgres