Concept · Designing databases

UNIQUE

UNIQUE prevents a value, or a combination of values, from repeating. A table can have several UNIQUE rules, and how NULL is treated depends on the engine.

Before continuing: This entry is part of the constraints and keys guide. If you are new to the topic, start with CREATE TABLE.

UNIQUE example

SQL
CREATE TABLE users_demo (
  id INTEGER PRIMARY KEY,
  email VARCHAR(200) NOT NULL UNIQUE
);

CREATE TABLE enrollments_demo (
  id INTEGER PRIMARY KEY,
  student_id INTEGER NOT NULL,
  course_id INTEGER NOT NULL,
  UNIQUE (student_id, course_id)
);

In users_demo, no email can repeat. In enrollments_demo, a student can appear in several courses and a course can have several students, but the same pair cannot be recorded twice.

How UNIQUE is used

In users_demo, no email can repeat. In enrollments_demo, a student can appear in several courses and a course can have several students, but the same pair cannot be recorded twice.

What changes from case to case

How NULL is treated inside a unique constraint is not the same on every engine. SQLite and PostgreSQL allow several NULL values by default; PostgreSQL also lets you specify NULLS NOT DISTINCT. SQL Server, by contrast, treats NULL as a value for the purposes of an ordinary unique key, so a nullable unique column accepts at most one NULL.

When a value must exist and must not repeat, state both rules: NOT NULL UNIQUE. Do not rely on how NULL behaves to define an identity.

Diagnosis on customers
SELECT email, COUNT(*) AS repetitions
FROM customers
WHERE email IS NOT NULL
GROUP BY email
HAVING COUNT(*) > 1;

SELECT COUNT(*) AS unknown_emails
FROM customers
WHERE email IS NULL;
Verified result on the teaching database
CheckResult
Repeated non-null emails0 groups
Unknown emails3 rows

Uniqueness can be added without cleaning up non-null duplicates. However, if the business rule says “every customer must have an email”, you also need to resolve those three NULL values and declare NOT NULL.

Common mix-ups with UNIQUE

Marking each column UNIQUE on its own

Not the same as a unique combination
student_id INTEGER UNIQUE,
course_id INTEGER UNIQUE

This definition would allow only one row per student and one row per course. To block only the duplicate pair, declare UNIQUE (student_id, course_id).