How can we set PRIMARY KEY on multiple columns of an existing MySQL table?

MySQLMySQLi Database

We can set PRIMARY KEY constraint on multiple columns of an existing table by using ADD keyword along with ALTER TABLE statement.

Example

Suppose we have a table ‘Room_allotment’ as follows −

mysql> Create table Room_allotment(Id Int, Name Varchar(20), RoomNo Int);
Query OK, 0 rows affected (0.20 sec)

mysql> Describe Room_allotment;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Id     | int(11)     | YES  |     | NULL    |       |
| Name   | varchar(20) | YES  |     | NULL    |       |
| RoomNo | int(11)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.11 sec)

Now we can add composite PRIMARY KEY on multiple columns, ‘id’ and ‘Name’, with the following query

mysql> Alter Table Room_allotment ADD PRIMARY KEY(Id, Name);
Query OK, 0 rows affected (0.29 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> Describe Room_allotment;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Id     | int(11)     | NO   | PRI | 0       |       |
| Name   | varchar(20) | NO   | PRI |         |       |
| RoomNo | int(11)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.12 sec)

It can be observed from the above result set that PRIMARY KEY has been added on multiple columns.

raja
Published on 18-Feb-2018 08:50:44
Advertisements