bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/SQL/SQL Database
SQL•SQL Database

SQL UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are unique.

Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

UNIQUE Constraint on CREATE TABLE

The following SQL defines a UNIQUE constraint for the "ID" column upon creation of the "Persons" table:

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)
);

Naming a Unique Constraint

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

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

UNIQUE Constraint on ALTER TABLE

To create a UNIQUE constraint on the "ID" column when the table is already created, use the following SQL syntax:

ALTER TABLE Persons
ADD UNIQUE (ID);

Naming a Unique Constraint

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

ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

Drop a UNIQUE Constraint

To drop a UNIQUE constraint, use the following SQL:

MySQL

ALTER TABLE Persons
DROP INDEX UC_Person;

SQL Server / Oracle / MS Access:

ALTER TABLE Persons
DROP CONSTRAINT UC_Person;

Previous

SQL NOT NULL Constraint

Next

SQL PRIMARY KEY Constraint

This chapter

Overview
21

Lessons

50m

Read time

1. SQL CREATE DATABASE Statement2. SQL DROP DATABASE Statement3. SQL BACKUP DATABASE Statement4. SQL CREATE TABLE Statement5. SQL DROP TABLE Statement6. SQL ALTER TABLE Statement7. SQL Constraints8. SQL NOT NULL Constraint9. SQL UNIQUE Constraint10. SQL PRIMARY KEY Constraint11. SQL FOREIGN KEY Constraint12. SQL CHECK Constraint13. SQL DEFAULT Constraint14. SQL CREATE INDEX Statement15. SQL AUTO INCREMENT Field16. SQL Working With Dates17. SQL Views18. SQL Injection19. SQL Parameters20. SQL Prepared Statements21. SQL Hosting

On this page

UNIQUE Constraint on CREATE TABLESQL Server / Oracle / MS Access:Naming a Unique ConstraintUNIQUE Constraint on ALTER TABLENaming a Unique ConstraintDrop a UNIQUE ConstraintSQL Server / Oracle / MS Access: