1This constraint ensures all values in a column are unique.
2Example 1 (MySQL): Adds a unique constraint to the id column when
3creating a new users table.
4CREATE TABLE users (
5id int NOT NULL,
6name varchar(255) NOT NULL,
7UNIQUE (id)
8);
9Example 2 (MySQL): Alters an existing column to add a UNIQUE
10constraint.
11ALTER TABLE users
12ADD UNIQUE (id);
1What is the difference between UNIQUE and PRIMARY KEY constraints?
2There should be only one PRIMARY KEY
3in a table whereas there can be
4any number of UNIQUE Keys.
5PRIMARY KEY doesn’t allow NULL
6values whereas Unique key allows NULL values.
1CREATE TABLE Students ( /* Create table with a single field as unique */
2 ID INT NOT NULL UNIQUE
3 Name VARCHAR(255)
4);
5
6CREATE TABLE Students ( /* Create table with multiple fields as unique */
7 ID INT NOT NULL
8 LastName VARCHAR(255)
9 FirstName VARCHAR(255) NOT NULL
10 CONSTRAINT PK_Student
11 UNIQUE (ID, FirstName)
12);
13
14ALTER TABLE Students /* Set a column as unique */
15ADD UNIQUE (ID);
16
17ALTER TABLE Students /* Set multiple columns as unique */
18ADD CONSTRAINT PK_Student /* Naming a unique constraint */
19UNIQUE (ID, FirstName);
20