Skip to content

UNIQUE KEY Unique constraint

The UNIQUE KEY constraint can be used to ensure that the values ​​of the columns or column groups of data rows to be inserted or updated are unique, that the values ​​of a column or a set of columns in any two rows of the table are not repeated, and that the unique key constraint must also be non-empty.

Syntax Description

> column_name data_type UNIQUE KEY;

Example

create table t1(a int unique key, b int, c int, unique key(b,c));
mysql> insert into t1 values(1,1,1);
Query OK, 1 row affected (0.01 sec)
mysql> insert into t1 values(2,1,1);
ERROR 1062 (HY000): Duplicate entry '(1,1)' for key '__mo_index_idx_col'
mysql> insert into t1 values(1,1,2);
ERROR 1062 (HY000): Duplicate entry '1' for key '__mo_index_idx_col'

Example Explanation: In the above example, there are two unique key constraint columns a and columns (b,c). When inserting data, the 2nd insert statement violates the unique constraint of (b,c) and repeats with the 1st insert value, so the insertion fails. Article 3 Insert statement violates the constraints of column a and therefore fails to insert.