As the name suggests, MySQL UNIQUE constraints maintain the uniqueness of columns in a table and do not allow the insertion of duplicate values. Basically, the UNIQUE constraint creates an index such that all values in the indexed column must be unique. It is worth mentioning here that there can be multiple UNIQUE columns in a MySQL table.
We can apply UNIQUE constraints by mentioning the "UNIQUE" keyword while defining the column. It can be understood with the help of the following example -
mysql> Create table test3(ID INT UNIQUE, Name Varchar(20)); Query OK, 0 rows affected (0.16 sec)
The above query creates a table named "test3" with "UNIQUE" constraint on the "ID" column. We can check using DESCRIBE statement as shown below-
mysql> DESCRIBE test3; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | ID | int(11) | YES | UNI | NULL | | | Name | varchar(20) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 2 rows in set (0.04 sec)
UNIQUE constraints can also be applied to the columns of the table by following query-
mysql> Create table test4(ID INT, Name Varchar(20),UNIQUE(ID)); Query OK, 0 rows affected (0.15 sec)
We can check using DESCRIBE statement as shown below -
mysql> DESCRIBE test4; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | ID | int(11) | YES | UNI | NULL | | | Name | varchar(20) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 2 rows in set (0.04 sec)
The above is the detailed content of What is MySQL UNIQUE constraint and how do we apply it to fields of a table?. For more information, please follow other related articles on the PHP Chinese website!