Tutorialspoint

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


1 Answer
karthikeya Boyini

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;

This will produce the following output −

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.