UNIQUE

SQL UNIQUE Constraint

UNIQUE ensures that all values in a column (or combination of columns) are different. A table can have many UNIQUE constraints but only one PRIMARY KEY.

Example

Create a Users table with a unique email and try it:

CREATE TABLE Users (
  UserID INTEGER PRIMARY KEY,
  Email  VARCHAR(255) NOT NULL UNIQUE,
  Name   VARCHAR(100)
);
INSERT INTO Users VALUES (1, '[email protected]', 'Asha');
INSERT INTO Users VALUES (2, '[email protected]', 'Vikram');
SELECT * FROM Users;

Result: 2 rows

UserIDEmailName
1[email protected]Asha
2[email protected]Vikram

Violation

INSERT INTO Users VALUES (3, '[email protected]', 'Another Asha');
-- Error: UNIQUE constraint failed: Users.Email

Multi-column UNIQUE and NULL

ALTER TABLE Employees
ADD CONSTRAINT UQ_Employee_Name UNIQUE (FirstName, LastName);

Most databases allow many NULLs in a UNIQUE column, because NULL is not equal to anything. SQL Server is the exception: it allows only one NULL (use a filtered unique index to allow more).