![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we enforce compound uniqueness in MySQL?
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)
Advertisements