Quick Links
MySQL Unique key in MySQL is a single field or combination of fields that ensure all values going to store into the column will be unique. It means a column cannot stores duplicate values.
MySQL allows us to use more than one column with UNIQUE constraint in a table.
Needs of Unique Key
- It is useful in preventing the two records from storing identical values into the column.
- Unique key stores only distinct values that maintain the integrity and reliability of the database for accessing the information in an organized way.
- It also works with a foreign key in preserving the uniqueness of a table.
- It can contain null value into the table.
Syntax:
The following syntax is used to create a unique key in MySQL.
CREATE TABLE table_name(
col1 datatype,
col2 datatype UNIQUE,
...
);
If we want to create more than one unique key column into a table, use the syntax as below:
CREATE TABLE table_name(
col1 col_definition,
col2 col_definition,
...
[CONSTRAINT constraint_name]
UNIQUE(column_name(s))
);
Unique Key Example
CREATE TABLE Student2 (
Stud_ID int NOT NULL UNIQUE,
Name varchar(45),
Email varchar(45),
Age int,
City varchar(25)
);