Can we enforce compound uniqueness in MySQL?

MySQLMySQLi Database

Yes, we can do that. To understand, let us first create a table −

mysql> create table enforceCompoundUniqueness
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(40) NOT NULL,
   -> StudentMobileNumber varchar(12) NOT NULL,
   -> UNIQUE StudentName_StudentMobileNumber(StudentName,StudentMobileNumber)
   -> );
Query OK, 0 rows affected (0.60 sec)

Following is the query to insert records in the table using insert command −

mysql> insert into enforceCompoundUniqueness(StudentName,StudentMobileNumber)
values('Larry','2322245676');
Query OK, 1 row affected (0.18 sec)

mysql> insert into enforceCompoundUniqueness(StudentName,StudentMobileNumber)
values('Larry','2322245676');
ERROR 1062 (23000): Duplicate entry 'Larry-2322245676' for key
'StudentName_StudentMobileNumber'

mysql> insert into enforceCompoundUniqueness(StudentName,StudentMobileNumber)
values('Sam','6475746455');
Query OK, 1 row affected (0.13 sec)

In the above query, if you try to insert duplicate records an error can be seen since we have enforced uniqueness.

Following is the query to display all records from the table using select statement −

mysql> select * from enforceCompoundUniqueness;

This will produce the following output −

+-----------+-------------+---------------------+
| StudentId | StudentName | StudentMobileNumber |
+-----------+-------------+---------------------+
| 1         | Larry       | 2322245676          |
| 3         | Sam         | 6475746455          |
+-----------+-------------+---------------------+
2 rows in set (0.00 sec)
raja
Published on 15-Apr-2019 12:42:48
Advertisements