How to insert auto_increment in an already created table in MySQL?


Use ALTER command for this. Let us first create a table −

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

Here is the query to insert auto_increment −

mysql> alter table DemoTable ADD COLUMN StudentId int NOT NULL;
Query OK, 0 rows affected (0.50 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> alter table DemoTable ADD PRIMARY KEY(StudentId);
Query OK, 0 rows affected (1.23 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> alter table DemoTable CHANGE StudentId StudentId int NOT NULL
AUTO_INCREMENT;
Query OK, 0 rows affected (2.20 sec)
Records: 0 Duplicates: 0 Warnings: 0

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentName) values('Chris');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(StudentName) values('David');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement

mysql> select *from DemoTable;

Output

This will produce the following output −

+-------------+-----------+
| StudentName | StudentId |
+-------------+-----------+
| Chris       | 1         |
| David       | 2         |
+-------------+-----------+
2 rows in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements