How can I enforce compound uniqueness in MySQL?

MySQLMySQLi Database

You can enforce compound uniqueness in MySQL with the help of UNIQUE keyword. Here is the syntax to add UNIQUE keyword to your table column.

The syntax is as follows

CREATE TABLE yourTableName
(
   yourColumnName1 datatype,
   yourColumnName2 datatype,
   yourColumnName3 datatype,
   .
   .
   N
   UNIQUE yourConstarintName(yourColumnName2,yourColumnName3)
);

To understand the above concept, let us create a table with some columns and add a unique constraint to a table. The query to create a table is as follows

mysql> create table UniqueDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(100),
   -> StudentAge int,
   -> StudentMarks int
   -> ,
   -> UNIQUE age_NameConstraint(StudentName,StudentAge)
   -> );
Query OK, 0 rows affected (0.76 sec)

You can display the constraints name from a table with the help of SHOW command.

The syntax is as follows

SHOW INDEX FROM yourTableName;

To display the unique constraint from a table, use the above syntax. The query is as follows −

mysql> SHOW INDEX FROM UniqueDemo;

The following is the output

+------------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
| Table      | Non_unique | Key_name           | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible |
+------------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
| uniquedemo |          0 | PRIMARY            |            1 | StudentId   | A         |           0 | NULL     | NULL   |      | BTREE      |         |               | YES     |
| uniquedemo |          0 | age_NameConstraint |            1 | StudentName | A         |           0 | NULL     | NULL   | YES  | BTREE      |         |               | YES     |
| uniquedemo |          0 | age_NameConstraint |            2 | StudentAge  | A         |           0 | NULL     | NULL   | YES  | BTREE      |         |               | YES     |
+------------+------------+--------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
3 rows in set (0.33 sec)
raja
Updated on 30-Jul-2019 22:30:25

Advertisements