1594

How can I reset the AUTO_INCREMENT of a field?

I want it to start counting from 1 again.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
homerun
  • 19,837
  • 15
  • 45
  • 70
  • 98
    You'll probably want to empty the table too: `TRUNCATE TABLE yourTableName;` – Konerak Jan 19 '12 at 08:41
  • I'd like to suggest that it shouldn't matter at all what your autoincrement values are. You shouldn't be relying on their values, or putting any significance on them. – Andy Lester Apr 05 '19 at 14:10
  • What for? I can't see the use case for this, unless you are cleaning up/truncating the whole table. – The Impaler Dec 09 '20 at 14:49
  • 4
    There are good options given in [How To Reset MySQL Autoincrement Column](http://viralpatel.net/blogs/reseting-mysql-autoincrement-column/) Note that `ALTER TABLE tablename AUTO_INCREMENT = value;` does *not* work for InnoDB – Naz Sep 19 '13 at 09:14
  • I am not an expert, but I use `TRUNCATE TABLE` to reset the entire table, including all the values. There are times when I want to reset the index, but not delete the table contents. The question doesn't say, but I got the sense they were asking how to reset the auto_increment, starting with 1. – TARKUS Feb 14 '23 at 23:02

25 Answers25

2545

You can reset the counter with:

ALTER TABLE tablename AUTO_INCREMENT = 1

InnoDB

For InnoDB you cannot set the auto_increment value lower or equal to the highest current index. (quote from ViralPatel):

Note that you cannot reset the counter to a value less than or equal to any that have already been used. For 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 plus one. For InnoDB, if the value is less than the current maximum value in the column, no error occurs and the current sequence value is not changed.

Aria

In a table with the Aria storage engine the auto_increment value can be set to any value, even lower than that of the current maximum. The next insert however will use the next available value (max + 1) ignoring the set value. If set to a higher value it will continue to use and increment from that. The documentation is not particular clear on that but this was observed with Mariadb 10.11.3

See also

See How can I reset an MySQL AutoIncrement using a MAX value from another table? on how to dynamically get an acceptable value.

theking2
  • 2,174
  • 1
  • 27
  • 36
Niels
  • 48,601
  • 4
  • 62
  • 81
  • 10
    This can take forever for a filled up table. Be careful with this: http://stackoverflow.com/questions/2681869/while-reseting-auto-increment-for-a-particular-table-query-is-taking-long-time – B T Aug 03 '12 at 21:11
  • 57
    this is a `circular reference` – Besnik Feb 21 '13 at 11:00
  • 97
    Bear in mind that MySql will create a new table, with the same structure and new auto_increment value and copy all records from the original table, drop the original and rename the new one. This could have a considerable performance impact (and disk space) on production environments if the table is large. – Rostol Sep 09 '13 at 20:18
  • 8
    @Rostol Does this problem exist even today (2021 with MySQL 8+)? I see that resetting AUTO_INCREMENT is instantaneous for even large tables. I kind of need the reset feature as I have ON DUPLICATE KEY UPDATE queries that unnecessarily increase the counter every time they are run. – workwise Sep 18 '21 at 09:59
161
SET  @num := 0;

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

ALTER TABLE your_table AUTO_INCREMENT =1;
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Nghiệp
  • 4,038
  • 2
  • 23
  • 27
76

Simply like this:

ALTER TABLE tablename AUTO_INCREMENT = value;

Reference: 13.1.9 ALTER TABLE Statement

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fyr
  • 20,227
  • 7
  • 37
  • 53
58

Enter image description here

There is a very easy way with phpMyAdmin under the "operations" tab. In the table options you can set autoincrement to the number you want.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Miles M.
  • 4,089
  • 12
  • 62
  • 108
44

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;

It's 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
salouri
  • 760
  • 1
  • 8
  • 19
37

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.

lreeder
  • 12,047
  • 2
  • 56
  • 65
28

Beware! TRUNCATE TABLE your_table will delete everything in your your_table.

You can also use the syntax TRUNCATE table like this:

TRUNCATE TABLE table_name
reformed
  • 4,505
  • 11
  • 62
  • 88
Manohar Kumar
  • 605
  • 9
  • 12
  • 27
    **New programmers**, be aware that `TRUNCATE` will also _delete ALL of your rows_ in specified table! – Zanshin13 Aug 05 '15 at 08:50
  • 1
    why delete all ? – M Amir Shahzad Oct 05 '21 at 21:51
  • 1
    this is not working by default, when you are working with foreign key constraints. better do it step by step and know what you are just doing. delete * from table; alter table auto_increment = 1; ... better way to avoid bad surprises! – Robert Fornesdale Nov 20 '22 at 08:52
  • According to mysql documentation this will also reset `AUTO_INCREMENT` as required. https://dev.mysql.com/doc/refman/8.0/en/truncate-table.html – Michael Currie Jan 21 '23 at 15:44
28

As of MySQL 5.6 you can use the simple ALTER TABLE with InnoDB:

ALTER TABLE tablename AUTO_INCREMENT = 1;

The documentation are updated to reflect this:

13.1.7 ALTER TABLE Statement

My testing also shows that the table is not copied. The value is simply changed.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SeanN
  • 633
  • 8
  • 11
14
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 dropped and then added back with previous settings. All the existent fields within the database table are filled in with the 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!!!.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alin Razvan
  • 1,451
  • 13
  • 18
14

It is for an empty table:

ALTER TABLE `table_name` AUTO_INCREMENT = 1;

If you have data, but you want to tidy up it, I recommend to 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`);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abdul Aziz Al Basyir
  • 1,104
  • 13
  • 28
10

To update to the latest plus one id:

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

Edit:

SET @latestId = SELECT MAX(id) FROM table_name;
SET @nextId = @latestId + 1;
ALTER TABLE table_name AUTO_INCREMENT = @nextId;

Not tested please test before you run*

darw
  • 941
  • 12
  • 15
narasimharaosp
  • 533
  • 3
  • 12
9

Warning: If your column has constraints or is connected as a foreign key to other tables this will have bad effects.

First, drop the column:

ALTER TABLE tbl_name DROP COLUMN column_id

Next, 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
reformed
  • 4,505
  • 11
  • 62
  • 88
bdalina
  • 503
  • 10
  • 16
8
ALTER TABLE tablename AUTO_INCREMENT = 1
Ryan M
  • 18,333
  • 31
  • 67
  • 74
8

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;

artsafin
  • 103
  • 2
  • 5
8
SET @num := 0;
UPDATE your_table SET id = @num := (@num+1);
ALTER TABLE your_table AUTO_INCREMENT =1;
Mihai Galan
  • 400
  • 4
  • 13
  • An explanation would be in order. E.g., what is the idea/gist? How is it different from other answers? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/57315051/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Aug 05 '21 at 19:43
  • @num should be the last Id number on the table. It will add 1 to this and set the next number of Id on insertion to this @Num+1. Then the auto_increment will be set to add 1 to the next ID every time an insertion occurs. Note that t:= and = do the very same thing. – Nandostyle Aug 29 '21 at 15:36
4

Try to 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 and then run this query:

  ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shabeer K
  • 1,489
  • 16
  • 23
3

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 another visual database design tool. I am going to show in Workbench how it is done - but it shouldn't be much different in other tools as well. By right clicking 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47
  • I'm using MySQL Workbench. None of the answers worked for me until I did Peter Mortensen's answer. Thank you. That worked! – Steve Stilson Jul 07 '23 at 20:46
2

If you're using PHPStorm's database tool you have to enter this in the database console:

ALTER TABLE <table_name> AUTO_INCREMENT = 0;
Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132
  • Just a NOTE - it does not have to be PHPStorm's database tool. If you are lucky enough to have the database hosted on a Server running Microsoft server O/S you can download MS Workbench and do this as well. – easleyfixed Jul 20 '22 at 19:42
1

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.

andromeda
  • 4,433
  • 5
  • 32
  • 42
1

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/reset-mysql-autoincrement-to-max-id-plus-1/ and adapted for Stack Overflow.

Kim Stacks
  • 10,202
  • 35
  • 151
  • 282
1
delete from url_rewrite where 1=1;
ALTER TABLE url_rewrite AUTO_INCREMENT = 1;

and then reindex

AbdulBasit
  • 1,269
  • 11
  • 19
0
ALTER TABLE `table_name`   DROP `id`;

ALTER TABLE `table_name` ADD `id` INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`id`) ;

Shortly,First we deleted id column then added it with primary key id again...

BARIS KURT
  • 477
  • 4
  • 15
  • 1
    May I request you to please add some more context around your answer. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. – RBT Jan 06 '17 at 23:24
  • Shortly,First we deleted id column then added it with primary key id again... – BARIS KURT Feb 27 '17 at 07:40
-3

The best way is remove the field with AI and add it again with AI. It works for all tables.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Grumpy
  • 2,140
  • 1
  • 25
  • 38
-5

You need to follow the advice from Miles M's comment and here is some PHP code that fixes the range in MySQL. Also you need to open up the my.ini file (MySQL) and change max_execution_time=60 to max_execution_time=6000; for large databases.

Don’t 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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Re *"Miles M's comment"*: Do you mean [Miles M's ***answer***](https://stackoverflow.com/questions/8923114/how-to-reset-auto-increment-in-mysql/23449385#23449385)? – Peter Mortensen Aug 05 '21 at 20:08
-6

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 a new row in the table.

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jeson
  • 1