SQL UNIQUE Constraint
UNIQUE A constraint in SQL used to ensure that all values in one or more columns are unique, which means there can be no duplicate values in the columns to which the constraint applies.
UNIQUE Similar to the PRIMARY KEY (PRIMARY KEY) constraint, but the UNIQUE constraint allows values in a column to be NULL, while the primary key does not.
The PRIMARY KEY constraint includes the functionality of a uniqueness (UNIQUE) constraint.
Each table can have multiple UNIQUE constraints, but only one PRIMARY KEY constraint can be defined.
Use Cases
- Ensuring Uniqueness: For example, ensuring that fields such as email addresses and usernames are unique across the entire table.
- Applying to Multiple Columns: You can create a
UNIQUEconstraint on multiple columns to ensure the uniqueness of combined values.
SQL UNIQUE Constraint with CREATE TABLE
When creating a table, you can define a UNIQUE constraint on a specific column or multiple columns to ensure that the values in those columns are unique within the table.
Add a UNIQUE constraint on the P_Id column of the "Persons" table UNIQUE Constraint
MySQL:
CREATE TABLE Persons (
P_Id INT NOT NULL,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
);
SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
P_Id INT NOT NULL UNIQUE,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255)
);
UNIQUE constraint and define a
To specify a name for a UNIQUE constraint and apply it to multiple columns, you can use the following syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
P_Id INT NOT NULL,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id, LastName)
);
Adding a UNIQUE Constraint with ALTER TABLE
If the table already exists, you can use the ALTER TABLE statement to add a UNIQUE constraint on a specified column.
Add a UNIQUE constraint on the "P_Id" UNIQUE Constraint
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD UNIQUE (P_Id);
Naming UNIQUE column and apply it to multiple columns
To name a UNIQUE constraint and define a UNIQUE constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id, LastName);
Drop a UNIQUE Constraint
If you need to remove a UNIQUE constraint, you can use the following SQL statement:
MySQL:
ALTER TABLE Persons
DROP INDEX uc_PersonID;
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
DROP CONSTRAINT uc_PersonID;