Home >Database >Mysql Tutorial >How to set PRIMARY KEY on multiple columns of a MySQL table?
Actually, MySQL allows us to set PRIMARY KEY on multiple columns. The advantage of this is that we can handle multiple columns as a single entity.
We create a table distribution by defining a composite primary key on multiple columns as shown below -
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 try to insert duplicate compound values in two columns, MySQL will throw the following error -
mysql> Insert Into allotment values(1, 'Aarav', 201),(2,'Harshit',201),(1,'Rahul ',201); ERROR 1062 (23000): Duplicate entry '1-201' for key 'PRIMARY'
The above is the detailed content of How to set PRIMARY KEY on multiple columns of a MySQL table?. For more information, please follow other related articles on the PHP Chinese website!