![]() |
VOOZH | about |
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:
Query:
INSERT INTO Employees (EmpID, Email)
VALUES (4, 'alex@example.com');
Error:
Syntax:
CREATE TABLE table_name (
column1 datatype UNIQUE,
column2 datatype,
...
);
In these examples, we demonstrate the implementation of SQL UNIQUE constraint:
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:
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:
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:
Query:
-- This will fail: duplicate CustomerIDโProductID pair
INSERT INTO Orders (OrderID, CustomerID, ProductID, OrderDate) VALUES
(3, 101, 501, '2024-01-15');
Error: