Home > Database > Mysql Tutorial > What is MySQL UNIQUE constraint and how do we apply it to fields of a table?

What is MySQL UNIQUE constraint and how do we apply it to fields of a table?

WBOY
Release: 2023-09-13 19:45:11
forward
966 people have browsed it

什么是 MySQL UNIQUE 约束以及我们如何将其应用于表的字段?

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

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

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

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

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!

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