Hostgre


HomeReferenceSQLSQL UNIQUE Constraint

SQL UNIQUE Constraint

The unique constraint ensures that all values in a column are totally different.
Both the unique and primary KEY constraints give a guarantee for singularity for a column or set of columns.
A PRIMARY KEY constraint automatically contains a unique constraint.
However, you'll be able to have several unique constraints per table, however only 1 PRIMARY KEY constraint per table.

SQL unique Constraint on create TABLE

The following SQL creates a unique constraint on the "ID" column once the "Persons" table is created:

SQL Server / Oracle / MS Access:

CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

MySQL:

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);

To name a unique constraint, and to define a unique constraint on multiple columns, use the subsequent SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

SQL unique Constraint on ALTER TABLE
To create a unique constraint on the "ID" column once the table is already created, use the subsequent SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons
ADD UNIQUE (ID);

To name a unique constraint, and to define a unique constraint on multiple columns, use the subsequent SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);
DROP a unique Constraint
To drop a unique constraint, use the subsequent SQL:

MySQL:

ALTER TABLE Persons
DROP INDEX UC_Person;
SQL Server / Oracle / MS Access:

ALTER TABLE Persons
DROP CONSTRAINT UC_Person;