Add an autoincrement column with a custom start value in MySQL

MySQLMySQLi Database

To add a new column to an already created table, use ALTER TABLE and ADD COLUMN. Use AUTO_INCREMENT to set auto increment custom value.

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Mike');
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 −

+-------------+
| StudentName |
+-------------+
| Robert      |
| Adam        |
| Mike        |
+-------------+
3 rows in set (0.00 sec)

Following is the query to add an autoincrement column with start value −

mysql> alter table DemoTable add column StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,AUTO_INCREMENT=1000;
Query OK, 0 rows affected (1.83 sec)
Records: 0 Duplicates: 0 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+-------------+-----------+
| StudentName | StudentId |
+-------------+-----------+
| Robert      |      1000 |
| Adam        |      1001 |
| Mike        |      1002 |
+-------------+-----------+
3 rows in set (0.00 sec)
raja
Published on 13-Dec-2019 10:54:18
Advertisements