How to form a composite key to be unique in MySQL?

MySQLMySQLi Database

To form a composite key to be unique, you need to use ADD UNIQUE command. Following is the syntax −

alter table yourTableName add unique
yourUniqueName( yourColumnName1,yourColumnName2,.......N);

Let us first create a table. Following is the query −

mysql> create table makeCompositeKeyDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(40),
   -> StudentAge int,
   -> StudentGrade char(1)
   -> );
Query OK, 0 rows affected (2.34 sec)

Now check the description of the table using DESC command. Following is the query −

mysql> desc makeCompositeKeyDemo;

This will produce the following output −

+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| Id           | int(11)     | NO   | PRI | NULL    | auto_increment |
| StudentName  | varchar(40) | YES  |     | NULL    |                |
| StudentAge   | int(11)     | YES  |     | NULL    |                |
| StudentGrade | char(1)     | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (1.65 sec)

Following is the query to form a composite key to be unique −

mysql> alter table makeCompositeKeyDemo add unique
Name_Age_Grade( StudentName,StudentAge,StudentGrade);
Query OK, 0 rows affected (0.69 sec)
Records: 0 Duplicates: 0 Warnings: 0

Now check the table description once again. Following is the query −

mysql> desc makeCompositeKeyDemo;

This will produce the following output −

+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| Id           | int(11)     | NO   | PRI | NULL    | auto_increment |
| StudentName  | varchar(40) | YES  | MUL | NULL    |                |
| StudentAge   | int(11)     | YES  |     | NULL    |                |
| StudentGrade | char(1)     | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
raja
Published on 15-Apr-2019 15:48:39
Advertisements