MySQL: Reset the Next Value in AUTO_INCREMENT column
This MySQL tutorial explains how to reset sequences using the AUTO_INCREMENT attribute in MySQL with syntax and examples.
Description
You can reset the next value assigned by the AUTO_INCREMENT at any time using the ALTER TABLE statement in MySQL.
Syntax
In MySQL, the syntax to reset the AUTO_INCREMENT column using the ALTER TABLE statement is:
table_name The name of the table whose AUTO_INCREMENT column you wish to reset. value The next value that will be used in the AUTO_INCREMENT column.
Example
Let’s look at an example of how to reset the next value assigned to an AUTO_INCREMENT column in a table in MySQL.
For example, if we had a suppliers table that was defined as follows:
We could reset the next value in the sequence for the supplier_id field (which is the AUTO_INCREMENT field in the suppliers table) with the following ALTER TABLE statement:
This example would change the next value in the AUTO_INCREMENT field (ie: next value in the sequence) to 1 for the supplier_id column in the suppliers table. Now when a new record is inserted into the suppliers table, the supplier_id column will be assigned the value of 1 in the newly created record.
Как сбрасывать значения автоинкремента в MySQL
Добавить в избранное
Главное меню » MySQL » Как сбрасывать значения автоинкремента в MySQL
Резюме : в этой статье мы покажем вам различные способы сброса значений автоинкремента столбцов AUTO_INCREMENT в MySQL.
M ySQL предоставляет вам полезную функцию под названием автоинкремент . Вы можете присвоить атрибут AUTO_INCREMENT столбцу таблицы, чтобы создать уникальный идентификатор для новой строки. Как правило, вы используете атрибут AUTO_INCREMENT для столбца первичного ключа таблицы.
Всякий раз, когда вы вставляете новую строку в таблицу, MySQL с помощью атрибута AUTO_INCREMENT автоматически присваивает порядковый номер столбцу.
Например, если в таблице восемь строк, и вы вставляете новую строку без указания значения для столбца автоинкремента, MySQL автоматически вставит новую строку id со значением 9.
Иногда вам может понадобиться сбросить значение столбца автоинкремента, чтобы идентификатор первой записи, который вы вставляете в таблицу, начинался с определенного числа, например, 1.
В MySQL вы можете сбросить значения автоинкремента различными способами.
Примеры сбрасывания значения автоматического приращения в MySQL
Сначала создайте таблицу с именем tmp и присвойте атрибут AUTO_INCREMENT столбцу id первичного ключа.
Во-вторых, вставьте пример данных в таблицу tmp:
В- третьих, запрос к таблице tmp для проверки операции вставки:
У нас есть три строки со значениями столбца ID: 1, 2 и 3. Отлично! Пора попрактиковаться в сбросе значения автоинкремента столбца ID.
Использование инструкции ALTER TABLE
Вы можете сбросить значение автоинкремента с помощью оператора ALTER TABLE. Синтаксис оператора ALTER TABLE для сброса значения автоинкремента выглядит следующим образом:
Вы указываете имя таблицы после оператора ALTER TABLE и имя value, которое вы хотите сбросить в выражении AUTO_INCREMENT=value.
Обратите внимание, что значение value должно быть больше или равно текущему максимальному значению столбца автоинкремента.
Давайте удалим последнюю запись в таблице tmp с id значением 3:
Если вы вставите новую строку, MySQL назначит 4 столбцу id новой строки. Однако вы можете сбросить число, сгенерированное MySQL, на 3, используя следующую инструкцию ALTER TABLE:
ALTER TABLE tmp AUTO_INCREMENT = 3;
Теперь давайте попробуем вставим новую строку в таблицу tmp и запросить данные из нее, чтобы увидеть эффект:
У нас есть три строки с последним значением автоинкремента, равным 3 вместо 4, что мы и ожидали.
Использование оператора TRUNCATE TABLE
Оператор TRUNCATE TABLE удаляет все данные из таблицы и сбрасывает значение автоинкремента на ноль.
Следующее иллюстрирует синтаксис оператора TRUNCATE TABLE:
Используя оператор TRUNCATE TABLE, вы удаляете все данные из таблицы навсегда и сбрасываете значение автоинкремента на ноль.
Использование операторов DROP TABLE и CREATE TABLE
Вы можете использовать пару операторов: DROP TABLE и CREATE TABLE, чтобы сбросить столбец автоинкремента. Обратите внимание, что этот метод удаляет все данные из таблицы навсегда.
Как и оператор TRUNCATE TABLE, эти операторы удаляют таблицу и воссоздают ее, поэтому значение автоинкремента сбрасывается на ноль.
В этой статье вы узнали, как различными способами сбросить значение автоинкремента в MySQL. Первый способ предпочтительнее, потому что он самый простой и не имеет побочных эффектов.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
MySQL Reset Auto Increment Values
Summary: in this tutorial, we will show you various ways to reset auto-increment values of AUTO_INCREMENT columns in MySQL.
MySQL provides you with a useful feature called auto-increment. You can assign the AUTO_INCREMENT attribute to a column of a table to generate a unique identity for the new row. Typically, you use the AUTO_INCREMENT attribute for the primary key column of the table.
Whenever you insert a new row into a table, MySQL automatically assigns a sequence number to the AUTO_INCREMENT column.
For example, if the table has eight rows and you insert a new row without specifying the value for the auto-increment column, MySQL will automatically insert a new row with id value 9.
Sometimes, you may need to reset the value of the auto-increment column so that the first record’s identity that you insert into the table starts from a specific number e.g., 1.
In MySQL, you can reset auto increment values in various ways.
MySQL reset auto increment value examples
First, create a table named tmp and assign the AUTO_INCREMENT attribute to the id primary key column.
Second, insert some sample data into the tmp table:
Third, query the tmp table to verify the insert operation:
We have three rows with values of ID column are 1, 2, and 3. Perfect! It is time to practice reset the auto-increment value of the ID column.
Using ALTER TABLE statement
You can reset the auto-increment value by using the ALTER TABLE statement. The syntax of the ALTER TABLE statement to reset the auto increment value is as follows:
You specify the table name after the ALTER TABLE clause and the value which you want to reset to in the expression AUTO_INCREMENT=value .
Notice that the value must be greater than or equal to the current maximum value of the auto-increment column.
Let’s delete the last record in the tmp table with id value 3:
If you insert a new row, MySQL will assign 4 to the id column of the new row. However, you can reset the number generated by MySQL to 3 by using the ALTER TABLE statement as the following:
Now, let’s try to insert a new row into the tmp table and query data from it to see the effect:
We have three rows with the last auto-increment value is 3 instead of 4, which is what we expected.
Using TRUNCATE TABLE statement
The TRUNCATE TABLE statement removes all the data from a table and resets the auto-increment value to zero.
The following illustrates the syntax of the TRUNCATE TABLE statement:
By using the TRUNCATE TABLE statement, you delete all data from the table permanently and reset the auto-increment value to zero.
Using DROP TABLE and CREATE TABLE statements
You can use a pair of statements: DROP TABLE and CREATE TABLE to reset the auto-increment column. Note that this method delete all data from the table permanently.
Like the TRUNCATE TABLE statement, those statements drop the table and recreate it, therefore, the value of the auto-increment is reset to zero.
In this tutorial, you have learned how to reset auto-increment value in MySQL in various ways. The first way is preferable because it is the easiest way and has no side effect.
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.
24 Answers 24
You can reset the counter with:
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.
Simply like this:
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.
The best solution that worked for me:
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.
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.