SQL UNIQUE Constraint
A UNIQUE
constraint in SQL ensures that all values in a column (or set of columns) are unique. This is a crucial constraint for maintaining data integrity and preventing duplicate entries.
UNIQUE Constraint: Definition and Usage
The UNIQUE
constraint guarantees that no two rows in a table will have the same value(s) in the specified column(s). This is similar to a primary key constraint, but a table can have multiple unique constraints, whereas it can only have one primary key. A primary key constraint automatically includes a unique constraint, but a unique constraint does not automatically include a primary key constraint. A primary key constraint enforces uniqueness and disallows null values, whereas a unique constraint enforces uniqueness but allows null values.
Adding UNIQUE Constraints
You can add UNIQUE
constraints when creating a table (using CREATE TABLE
) or later using ALTER TABLE
.
UNIQUE Constraint on CREATE TABLE
This example creates the 'Persons' table with a unique constraint on the 'ID' column.
Syntax (SQL Server, Oracle, MS Access)
CREATE TABLE Persons (
ID INT NOT NULL UNIQUE,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Age INT
);
Syntax (MySQL)
CREATE TABLE Persons (
ID INT NOT NULL,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Age INT,
UNIQUE (ID)
);
Output
Creates a 'Persons' table. The 'ID' column will not allow duplicate values. Note the different syntax for MySQL compared to other systems.
Named UNIQUE Constraints and Multiple Columns
You can give your constraint a name and apply it across multiple columns.
Syntax
CREATE TABLE Persons (
ID INT NOT NULL,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Age INT,
CONSTRAINT UC_Person UNIQUE (ID, LastName)
);
Output
Creates a 'Persons' table with a named unique constraint ('UC_Person'). The combination of 'ID' and 'LastName' must be unique across rows.
Adding a UNIQUE Constraint After Table Creation
Use ALTER TABLE
to add a unique constraint to an existing table.
Syntax
ALTER TABLE Persons
ADD UNIQUE (ID);
--Named constraint and multiple columns:
ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID, LastName);
Output
Adds a unique constraint to the 'Persons' table. Existing data must satisfy the constraint; otherwise, an error will occur.
Dropping UNIQUE Constraints
To delete a unique constraint, use DROP INDEX
(MySQL) or DROP CONSTRAINT
(other database systems).
Syntax (MySQL)
ALTER TABLE Persons
DROP INDEX UC_Person;
Syntax (SQL Server, Oracle, MS Access)
ALTER TABLE Persons
DROP CONSTRAINT UC_Person;
Output
The unique constraint 'UC_Person' is removed from the 'Persons' table.