SQL UNIQUE
UNIQUE guarantees no two rows share the column's value. The database enforces it with an index.
Single-column unique
SQL
CREATE TABLE customers ( id INT PRIMARY KEY, email VARCHAR(120) UNIQUE );
Composite unique
Unique applied to several columns means the combination must be unique, but each individual column can repeat:
SQL
CREATE TABLE memberships ( user_id INT, team_id INT, joined_at DATETIME, CONSTRAINT uq_user_team UNIQUE (user_id, team_id) );
Add or drop later
SQL
ALTER TABLE customers ADD CONSTRAINT uq_email UNIQUE (email); ALTER TABLE customers DROP CONSTRAINT uq_email;
UNIQUE and NULL
| DB | Treats multiple NULLs as… |
|---|---|
| MySQL / PostgreSQL / SQLite | Allowed — many rows may all be NULL. |
| SQL Server | Only one NULL permitted by default. |
PRIMARY KEY vs UNIQUE
- A table can have one
PRIMARY KEYbut manyUNIQUEs. - PRIMARY KEY implies
NOT NULL; UNIQUE does not.
Tip: Add
UNIQUE on natural identifiers — email, slug, SKU — even if you also have a numeric primary key. It guards against duplicate-account bugs.Example
Exercise
Enforce that no two customers share an email.
email VARCHAR(120)
Six letters; the no-duplicates constraint.
Discussion
Loading…