Createtabletest3(IDINTUNIQUE,NameVarchar(20));QueryOK,0rowsaffected(0.16sec) The above query creates a file named"/> Createtabletest3(IDINTUNIQUE,NameVarchar(20));QueryOK,0rowsaffected(0.16sec) The above query creates a file named">

Home  >  Article  >  Database  >  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
WBOYforward
2023-09-13 19:45:11878browse

什么是 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)

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)

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)

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)

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!

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