DESCRIBETEST5;+ -------+-------------+------+-----+---------"/> DESCRIBETEST5;+ -------+-------------+------+-----+---------">
Home >Database >Mysql Tutorial >Besides the ALTER TABLE statement, which statement can be used to apply a UNIQUE constraint on a field of an existing MySQL table?
The CREATE UNIQUE INDEX statement can also be used to apply UNIQUE constraints to fields of an existing MySQL table. Its syntax is as follows -
CREATE UNIQUE INDEX index_name ON table_name(Column_name);
Suppose we have a table named "Test5" and we want to add a UNIQUE constraint to the "ID" column, then we can use CREATE UNIQUE INDEX To complete the command as follows -
mysql> DESCRIBE TEST5; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | ID | int(11) | YES | | NULL | | | Name | varchar(20) | YES| | NULL | | +-------+-------------+------+-----+---------+-------+ 2 rows in set (0.04 sec) mysql> CREATE UNIQUE INDEX ID_UNQ ON TEST5(ID); Query OK, 0 rows affected (0.20 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESCRIBE test5; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | ID | int(11) | YES | UNI | NULL | | | Name | varchar(20) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 2 rows in set (0.04 sec)
From the result set of the above query, it can be seen that the column ID has a UNIQUE constraint.
The above is the detailed content of Besides the ALTER TABLE statement, which statement can be used to apply a UNIQUE constraint on a field of an existing MySQL table?. For more information, please follow other related articles on the PHP Chinese website!