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?

王林
Release: 2023-09-11 19:45:03
forward
1424 people have browsed it

除了 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);
Copy after login

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)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template