SQL - UNIQUE


Advertisements

Previous Page Next Page

The SQL UNIQUE constraint is used to ensure that all values in a column of a table are different (unique). To ensure uniqueness of values in a column either UNIQUE or PRIMARY KEY constraints can be used. A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, a table can have only one PRIMARY KEY constraint, but many UNIQUE constraints.

SQL UNIQUE constraint with CREATE TABLE statement

The below mentioned SQL code creates a table called Employee which contains five columns: EmpID, Name, City, Age and Salary in which UNIQUE constraint is applied on column EmpID.

SQL Server / Oracle / MS Access

CREATE TABLE Employee (
  EmpID INT NOT NULL      UNIQUE,
  Name VARCHAR(255),
  City VARCHAR(100),
  Age INT,
  Salary DECIMAL(18,2)
);

MySQL

CREATE TABLE Employee (
  EmpID INT NOT NULL,
  Name VARCHAR(255),
  City VARCHAR(100),
  Age INT,
  Salary DECIMAL(18,2).
  UNIQUE(EmpID)
);

To provide a name to UNIQUE constraint, and to define a UNIQUE constraint on multiple columns (say EmpID and Name), the SQL code is given below:

MySQL / SQL Server / Oracle / MS Access

CREATE TABLE Employee (
  EmpID INT NOT NULL,
  Name VARCHAR(255),
  City VARCHAR(100),
  Age INT,
  Salary DECIMAL(18,2),
  CONSTRAINT UC_Employee UNIQUE(EmpID, Name)
);

SQL UNIQUE constraint with ALTER TABLE statement

In the above example, a table called Employee is created. To enforce UNIQUE constraint on Salary column, the SQL code is given below:

MySQL / SQL Server / Oracle / MS Access

ALTER TABLE Employee
ADD UNIQUE (Salary);

To provide a name to UNIQUE constraint, and to define a UNIQUE constraint on multiple columns (say Age and Salary), the SQL code is given below:

MySQL / SQL Server / Oracle / MS Access

ALTER TABLE Employee
ADD CONSTRAINT UC_Employee UNIQUE (Age, Salary);

DROP UNIQUE constraint

To drop UC_Employee UNIQUE constraint from table called Employee, the SQL code is given below:

MySQL

ALTER TABLE Employee
DROP INDEX UC_Employee;

SQL Server / Oracle / MS Access

ALTER TABLE Employee
DROP CONSTRAINT UC_Employee;

Previous Page Next Page
Advertisements