UNIQUE stops two rows from holding the same value in a column, or the same combination of values across several columns. It suits anything that must not repeat but is not the table’s main identifier.
One column
Section titled “One column”No two approved suppliers should share a name:
CREATE TABLE Suppliers ( SupplierID int PRIMARY KEY, Name varchar(100) NOT NULL UNIQUE, Service varchar(50), City varchar(50));A combination of columns
Section titled “A combination of columns”Suppliers number their own invoices, and two suppliers may well use the same number. What must not happen is the same supplier’s invoice number being entered twice, which is how invoices get paid twice. The rule covers the pair of columns:
CREATE TABLE Invoices ( InvoiceID int PRIMARY KEY, Supplier varchar(100) NOT NULL, SupplierRef varchar(30), Amount decimal(10, 2) NOT NULL, CONSTRAINT UQ_SupplierRef UNIQUE (Supplier, SupplierRef));With Hartwell Lighting’s invoice HL-2207 already recorded:
- Entering
HL-2207from Hartwell Lighting again is refused. - Entering
HL-2207from Kestrel Catering is accepted, since the pair is different.
On an existing table
Section titled “On an existing table”ALTER TABLE InvoicesADD CONSTRAINT UQ_SupplierRef UNIQUE (Supplier, SupplierRef);To remove it, drop it by name: ALTER TABLE Invoices DROP CONSTRAINT UQ_SupplierRef;. MySQL writes this as DROP INDEX UQ_SupplierRef.
UNIQUE and empty values
Section titled “UNIQUE and empty values”Most databases, including PostgreSQL, MySQL, Oracle and SQLite, let several rows leave a unique column empty, since one NULL is not equal to another. SQL Server is the exception, and allows only one NULL in a unique column.
UNIQUE and PRIMARY KEY
Section titled “UNIQUE and PRIMARY KEY”A primary key is unique too, but a table has only one primary key, and it can never be empty. A table can have as many UNIQUE constraints as it needs.