SQLite UNIQUE Constraint
UNIQUE
UNIQUE makes sure that all the values in a column are different.
Example
CREATE TABLE IF NOT EXISTS Users (
UserID INTEGER PRIMARY KEY,
Email TEXT UNIQUE,
Name TEXT
);
Try it Yourself »
Breaking the Rule
The second insert uses the same email as the first, so it gives an error:
Example
CREATE TABLE IF NOT EXISTS Users (
UserID INTEGER PRIMARY KEY,
Email TEXT UNIQUE,
Name TEXT
);
INSERT INTO Users (Email, Name)
VALUES ('emil@example.com', 'Emil');
INSERT INTO Users (Email, Name)
VALUES ('emil@example.com', 'Tobias');
Try it Yourself »
UNIQUE on More Than One Column
A table constraint can make a combination of columns unique. In this example, the same person can only have one membership in each club:
Example
CREATE TABLE IF NOT EXISTS Memberships (
PersonName TEXT,
Club TEXT,
UNIQUE (PersonName, Club)
);
Try it Yourself »
UNIQUE on an Existing Table
SQLite cannot add a UNIQUE constraint with ALTER TABLE. Create a unique index instead. It works in the same way:
Example
CREATE UNIQUE INDEX IF NOT EXISTS idx_shippername
ON Shippers (ShipperName);
Try it Yourself »
Note: A UNIQUE column can have many NULL values, because one NULL is never equal to another NULL.