SQL UNIQUE Constraint (original) (raw)

Last Updated : 10 Feb, 2026

The UNIQUE constraint in SQL prevents duplicate entries in specified column(s) while still allowing multiple NULL values. It helps maintain data accuracy without the strict non-NULL requirement of a PRIMARY key.

**Query:

CREATE TABLE Employees (
EmpID INT,
Email VARCHAR(100) UNIQUE
);

-- Insert data into Employees table
INSERT INTO Employees (EmpID, Email) VALUES
(1, 'alex@example.com'),
(2, NULL),
(3, NULL); -- Allowed because multiple NULLs are treated as unique

**Output:

Screenshot-2025-11-20-095252

Employees Table

**Query:

INSERT INTO Employees (EmpID, Email)
VALUES (4, 'alex@example.com');

**Error:

Screenshot-2025-11-20-095323

**Syntax:

CREATE TABLE table_name (
 column1 datatype UNIQUE,
 column2 datatype,
 ...
);

Example of Using the SQL UNIQUE Constraint

In these examples, we demonstrate the implementation of SQL UNIQUE constraint:

Example 1: Creating a Table with UNIQUE Constraints

Let's create a Customers table where the Email column must be unique.

**Query:

CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(100),
Email VARCHAR(100) UNIQUE,
Country VARCHAR(50)
);

--Insert data into Customers table
INSERT INTO Customers (CustomerID, Name, Email, Country) VALUES
(1, 'John Doe', 'john.doe@example.com', 'USA'),
(2, 'Jane Smith', 'jane.smith@example.com', 'Canada');

**Output:

Screenshot-2025-11-20-101047

Customers Table

**Query:

-- This will fail because 'john.doe@example.com' already exists
INSERT INTO Customers (CustomerID, Name, Email, Country) VALUES
(3, 'Alice Johnson', 'john.doe@example.com', 'UK');

**Error:

Screenshot-2025-11-20-101426

Example 2: Using UNIQUE with Multiple Columns

We can also apply the UNIQUE constraint to multiple columns to ensure that the combination of those columns is unique.

**Query:

CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
ProductID INT,
OrderDate DATE,
UNIQUE (CustomerID, ProductID)
);

--Insert data into Orders table
INSERT INTO Orders (OrderID, CustomerID, ProductID, OrderDate) VALUES
(1, 101, 501, '2024-01-10'),
(2, 102, 501, '2024-01-12');

**Output:

Screenshot-2025-11-20-102343

Orders Table

**Query:

-- This will fail: duplicate CustomerID–ProductID pair
INSERT INTO Orders (OrderID, CustomerID, ProductID, OrderDate) VALUES
(3, 101, 501, '2024-01-15');

**Error:

Screenshot-2025-11-20-103527