How can we change MySQL AUTO_INCREMENT starting number?


MySQL AUTO_INCREMENT value starts from 1 but we can change it with the help of following two ways −

With the help of ALTER TABLE query

We can use ALTER TABLE query to change the staring value of AUTO_INCREMENT as follows −

ALTER TABLE table_name AUTO_INCREMENT = value;

Example

Suppose we have created a table having column ‘id’ as AUTO_INCREMENT. Now if we will insert the values in it then the sequence number would start from 1 as you can see this in following queries −

mysql> Create Table EMP(id int NOT NULL PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(10));
Query OK, 0 rows affected (0.07 sec)

mysql> Insert Into EMP(Name) Values('Aryan');
Query OK, 1 row affected (0.02 sec)

mysql> Insert Into EMP(Name) Values('Yash');
Query OK, 1 row affected (0.04 sec)

mysql> Select * from EMP;
+----+-------+
| id | NAME  |
+----+-------+
| 1  | Aryan |
| 2  | Yash  |
+----+-------+
2 rows in set (0.00 sec)

Now, if we want to change the sequence number afterward then we need to use ALTER TABLE query to change the value of AUTO_INCREMENT as follows −

mysql> Alter table emp auto_increment = 10;
Query OK, 2 rows affected (0.25 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Insert Into EMP(Name) Values('Daksh');
Query OK, 1 row affected (0.03 sec)

mysql> Insert Into EMP(Name) Values('Shayra');
Query OK, 1 row affected (0.06 sec)

mysql> Select * from EMP;
+----+--------+
| id | NAME   |
+----+--------+
| 1  | Aryan  |
| 2  | Yash   |
| 10 | Daksh  |
| 11 | Shayra |
+----+--------+
4 rows in set (0.00 sec)

The query above has changed the value of AUTO_INCREMENT to 10 hence on inserting new values after that we will get the sequence number from 10 onwards.

With the help of CREATE TABLE query

We can also change the AUTO_INCREMENT value while creating the table. It can be done by specifying the value of AUTO_INCREMENT with CREATE TABLE query as follows −

CREATE TABLE (Column1 INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Column2 data type) AUTO_INCREMENT = value;

Example

mysql> Create Table EMP1(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(10)) AUTO_INCREMENT = 100;
Query OK, 0 rows affected (0.11 sec)

The query above specified the value of AUTO_INCREMENT to 100 at the creation of the table. Now if we will insert the values in it then the sequence number would start from 100 instead of by default value 1 as follows −

mysql> Insert into emp1(name) values('Sohan');
Query OK, 1 row affected (0.04 sec)

mysql> Insert into emp1(name) values('Harshit');
Query OK, 1 row affected (0.05 sec)

mysql> Select * from emp1;
+-----+---------+
| id  | NAME    |
+-----+---------+
| 100 |   Sohan |
| 101 | Harshit |
+-----+---------+
2 rows in set (0.00 sec)

Updated on: 20-Jun-2020

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements