Home > Database > Mysql Tutorial > How can we apply UNIQUE constraints on fields of existing MySQL table?

How can we apply UNIQUE constraints on fields of existing MySQL table?

PHPz
Release: 2023-09-16 21:05:02
forward
1191 people have browsed it

我们如何对现有 MySQL 表的字段应用 UNIQUE 约束?

We can apply UNIQUE constraints to columns of existing MySQL tables with the help of ALTER TABLE statement.

Syntax

ALTER TABLE table_name MODIFY colum_name datatype UNIQUE;
                    OR
ALTER TABLE table_name ADD UNIQUE (colum_name);
Copy after login

Example

Suppose we have a table named "Test4" and we want to add a UNIQUE constraint to the "Name" column, then we can use ALTER The TABLE command is used to complete the following -

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)

mysql> ALTER TABLE test4 MODIFY Name Varchar(20) UNIQUE;
Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> DESCRIBE test4;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID    | int(11)     | YES  | UNI | NULL    |       |
| Name  | varchar(20) | YES  | UNI | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.04 sec)
Copy after login

As can be seen from the above result set, MySQL has added a UNIQUE constraint to the field "Name". We can also add UNIQUE constraints using the following query -

mysql> Alter table test4 add UNIQUE(name);
Query OK, 0 rows affected (0.16 sec)
Records: 0 Duplicates: 0 Warnings: 0
Copy after login

The above is the detailed content of How can we apply UNIQUE constraints on fields of 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