UNIQUE Constraint
beginnerbasics
2 min read
What is a UNIQUE Constraint?
The UNIQUE constraint ensures that all values in a column (or combination of columns) are different across every row. It prevents duplicate entries for things like email addresses, usernames, or product codes.
Syntax
Column-level:
CREATE TABLE students (
id SERIAL PRIMARY KEY,
email VARCHAR(100) UNIQUE
);Table-level (multi-column):
CREATE TABLE enrollments (
student_id INT,
course_id INT,
UNIQUE (student_id, course_id)
);When to Use
- Ensuring email addresses are unique per user
- Preventing duplicate enrollments for the same student in the same course
- Enforcing business rules that require distinct values
Key Points
- Allows One NULL — Unlike PRIMARY KEY, a UNIQUE column can contain NULL values (multiple NULLs are allowed since NULL is not equal to NULL).
- Auto Index — PostgreSQL creates a unique B-tree index automatically.
- Multiple Allowed — A table can have many UNIQUE constraints.
- Named Constraints — You can name them for clarity: CONSTRAINT uq_email UNIQUE (email).
- Composite — A multi-column UNIQUE constraint enforces uniqueness on the combination of values.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
UNIQUE Constraint Challenge
Write a query that solve this task: ensure no two students share the same email.
Expected result
The students table is created. Inserting a duplicate email will raise an error.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What is a UNIQUE Constraint?
Initializing database...Each run starts from fresh sample data.
More Examples
Composite unique constraint
Prevent a student from enrolling in the same course twice.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
Can a UNIQUE column contain NULL?
Yes. In PostgreSQL, multiple NULLs are allowed in a UNIQUE column because NULL is considered distinct from other NULLs.
How is UNIQUE different from PRIMARY KEY?
PRIMARY KEY = UNIQUE + NOT NULL, and only one per table. You can have many UNIQUE constraints, and they allow NULLs.