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?

Besides the ALTER TABLE statement, which statement can be used to apply a UNIQUE constraint on a field of an existing MySQL table?

王林
王林forward
2023-09-11 19:45:031493browse

除了 ALTER TABLE 语句之外,还有哪个语句可用于对现有 MySQL 表的字段应用 UNIQUE 约束?

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);

Example

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete