Autoincrement in MySQL begins from 1? How can we begin it from another number?


The autoincrement in MySQL gives a unique number every time. By default, it starts at 1. If you want to start from another number, then you need to change the auto-increment value with the help of ALTER command or you can give value at the time of table creation.

Let us first create a table −

mysql> create table DemoTable
(
   UniqueNumber int NOT NULL AUTO_INCREMENT,
   PRIMARY KEY(UniqueNumber)
);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------+
| UniqueNumber |
+--------------+
|            1 |
|            2 |
|            3 |
|            4 |
+--------------+
4 rows in set (0.00 sec)

Following is the query to change the auto_increment value to begin from another number −

mysql> alter table DemoTable AUTO_INCREMENT=1000;
Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0

Insert some records in the table using insert command −

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output. Now the new auto_increment value inserted and begins from 1000 −

+--------------+
| UniqueNumber |
+--------------+
|            1 |
|            2 |
|            3 |
|            4 |
|         1000 |
|         1001 |
|         1002 |
+--------------+
7 rows in set (0.00 sec)

Updated on: 03-Oct-2019

445 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements