ALTER table by adding AUTOINCREMENT in MySQL?

MySQLMySQLi Database

To add AUTOINCREMENT in MySQL, you can use the ALTER command.

ALTER TABLE yourTableName change yourColumName yourColumnName dataType AUTO_INCREMENT PRIMARY KEY;

To understand the above concept, create a table with a column. Let us create a table −

mysql> create table AlterTableToAddAutoIncrement
   -> (
   -> StudentId int
   -> );
Query OK, 0 rows affected (0.57 sec)

Implement the above syntax to change “StudentId” with AUTOINCREMENT. The query is as follows −

mysql> alter table AlterTableToAddAutoIncrement change StudentId StudentId int AUTO_INCREMENT Primary  key;
Query OK, 0 rows affected (1.93 sec)
Records: 0 Duplicates: 0 Warnings: 0

We have added AUTO_INCREMENT to column name ‘StudentId’. Now you can verify whether autoincrement is working or not by inserting records without giving any value.

The query is as follows −

mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.33 sec)

Now you can display all records which will be displayed in sequence of 1, 2, 3, 4, etc. The query is as follows −

mysql> select *from AlterTableToAddAutoIncrement;

The following is the output −

+-----------+
| StudentId |
+-----------+
|         1 |
|         2 |
|         3 |
+-----------+
3 rows in set (0.00 sec)
raja
Published on 24-Dec-2018 11:04:19
Advertisements