iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

DBTreats multiple NULLs as…
MySQL / PostgreSQL / SQLiteAllowed — many rows may all be NULL.
SQL ServerOnly one NULL permitted by default.

PRIMARY KEY vs UNIQUE

  • A table can have one PRIMARY KEY but many UNIQUEs.
  • 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

Example
ALTER TABLE customers
ADD CONSTRAINT uq_email UNIQUE (email);
Try it Yourself »

Exercise

Enforce that no two customers share an email.

email VARCHAR(120)

Test yourself

Q1. A UNIQUE constraint is enforced by…
Q2. SQL Server, by default, treats multiple NULLs in a UNIQUE column as…
Q3. A composite UNIQUE on (a, b) means…

Discussion

Loading…