![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to change a primary key in MySQL to auto_increment?\n
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.
Advertisements