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


Actually, MySQL allows us to set PRIMARY KEY on multiple columns. The advantage of doing this is that we can work on multiple columns as a single entity.

Example

We have created the table allotment by defining composite PRIMARY KEY on multiple columns as follows −

mysql> Create table allotment(
   RollNo Int, Name Varchar(20), RoomNo Int, PRIMARY KEY(RollNo, RoomNo));
Query OK, 0 rows affected (0.23 sec)

mysql> Describe allotment;

+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| RollNo | int(11)     | NO   | PRI | 0       |       |
| Name   | varchar(20) | YES  |     | NULL    |       |
| RoomNo | int(11)     | NO   | PRI | 0       |       |
+--------+-------------+------+-----+---------+-------+

3 rows in set (0.10 sec)

Now, when we will try to insert the duplicate composite values in both the columns then MySQL throws an error as follows −

mysql> Insert Into allotment values(1, 'Aarav', 201),(2,'Harshit',201),(1,'Rahul ',201);
ERROR 1062 (23000): Duplicate entry '1-201' for key 'PRIMARY'

Updated on: 30-Jul-2019

742 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements