How to change auto increment number in MySQL?

MySQLMySQLi Database

The auto_increment is a default property that automatically increments the newly added record by 1. The starting number can be changed with the help of the alter command.

First, a table is created with the help of the insert command. This is given as follows −

mysql> CREATE table AutoIncrementTable
-> (
-> id int auto_increment,
-> name varchar(200),
-> Primary key(id)
-> );
Query OK, 0 rows affected (0.70 sec)

After creating the table, records are inserted into the table with the help of the insert command This is given as follows −

mysql> INSERT into AutoIncrementTable(name) values('Carol');
Query OK, 1 row affected (0.19 sec)

mysql> INSERT into AutoIncrementTable(name) values('Bob');
Query OK, 1 row affected (0.15 sec)

mysql> INSERT into AutoIncrementTable(name) values('John');
Query OK, 1 row affected (0.18 sec)

Now, the records in the table can be seen with the help of the select command. This is given as follows −

mysql> SELECT * from AutoIncrementTable;

The output obtained from the above query is given below −

+----+-------+
| id | name  |
+----+-------+
| 1  | Carol |
| 2  | Bob   |
| 3  | John  |
+----+-------+
3 rows in set (0.00 sec)

Now, three records have been inserted in the table and the id is incremented by 1 each time. Now the Auto Increment is changed so that the id of the next record starts from 1000.

The syntax to change the auto_increment is given as follows.

alter table yourTableName auto_increment=startingNumber;

The above syntax is used to change the auto_increment by 1000. This is shown below −

mysql> alter table AutoIncrementTable auto_increment = 1000;
Query OK, 0 rows affected (0.16 sec)
Records: 0 Duplicates: 0 Warnings: 0

After successfully changing the auto_increment, more recors are inserted into the table. This is shown below −

mysql> INSERT into AutoIncrementTable(name) values('Taylor');
Query OK, 1 row affected (0.12 sec)

mysql> INSERT into AutoIncrementTable(name) values('Sam');
Query OK, 1 row affected (0.17 sec)

Now, the table records are viewed using the select statement. It can be seen that the 4th record number starts from 1000.

mysql> SELECT * from AutoIncrementTable;

The following is the output

+------+--------+
| id   | name   |
+------+--------+
| 1    | Carol  |
| 2    | Bob    |
| 3    | John   |
| 1000 | Taylor |
| 1001 | Sam    |
+------+--------+
5 rows in set (0.00 sec)
raja
Published on 18-Oct-2018 09:18:12
Advertisements