How do I drop a primary key in MySQL?


To drop a primary key, use ALTER at first to alter the table. With that, use DROP to drop the key as in the below

Syntax

alter table yourTableName drop primary key;

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> StudentId int NOT NULL,
   -> StudentName varchar(20),
   -> StudentAge int,
   -> primary key(StudentId)
   -> );
Query OK, 0 rows affected (0.48 sec)

Here is the query to check the description of table −

mysql> desc DemoTable;

This will produce the following output−

+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| StudentId   | int(11)     | NO   | PRI | NULL    |       |
| StudentName | varchar(20) | YES  |     | NULL    |       |
| StudentAge  | int(11)     | YES  |     | NULL    |       |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

Following is the query to drop a primary key in MySQL −

mysql> alter table DemoTable drop primary key;
Query OK, 0 rows affected (1.70 sec)
Records: 0 Duplicates: 0 Warnings: 0

Let us check the table description once again −

mysql> desc DemoTable;

This will produce the following output −

+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| StudentId   | int(11)     | NO   |     | NULL    |       |
| StudentName | varchar(20) | YES  |     | NULL    |       |
| StudentAge  | int(11)     | YES  |     | NULL    |       |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

Updated on: 18-Dec-2019

399 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements