To change a primary key to auto_increment, you can use MODIFY command. Let us first create a table.
mysql> create table changePrimaryKeyInAutoIncrement -> ( -> StudentId int not null primary key, -> StudentName varchar(100), -> StudentAge int, -> StudentAddress varchar(100) -> ); Query OK, 0 rows affected (0.63 sec)
Let us now check the description of table using desc command:
mysql> desc changePrimaryKeyInAutoIncrement;
This will produce the following output
+----------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------------+--------------+------+-----+---------+-------+ | StudentId | int(11) | NO | PRI | NULL | | | StudentName | varchar(100) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentAddress | varchar(100) | YES | | NULL | | +----------------+--------------+------+-----+---------+-------+ 4 rows in set (0.00 sec)
Look at the above sample output, StudentId column is a primary key. Now let us change the primary key to auto_increment:
mysql> alter table changePrimaryKeyInAutoIncrement MODIFY StudentId INT AUTO_INCREMENT; Query OK, 0 rows affected (1.48 sec) Records: 0 Duplicates: 0 Warnings: 0
Let us check the table description of once again:
mysql> desc changePrimaryKeyInAutoIncrement;
This will produce the following output
+----------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(100) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentAddress | varchar(100) | YES | | NULL | | +----------------+--------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec)
Look at the above sample output, StudentId column has been changed to auto_increment.