Sub topic 11
Unique Indexes and Constraints
Assume you know SELECT, WHERE, primary keys, and basic B-tree indexes. This chapter uses PostgreSQL syntax.
A unique constraint requires each non-duplicate value in one or more columns. It protects a rule about the data, such as “each email address identifies at most one user.” PostgreSQL usually enforces the constraint with a unique B-tree index.
Constraint or unique index?
A unique constraint expresses a business rule in the table definition. A unique index is an access structure that also rejects duplicate keys. Both can prevent duplicates, but they communicate different intent.
CREATE TABLE users (
user_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
display_name text NOT NULL,
CONSTRAINT users_email_unique UNIQUE (email)
);
CREATE UNIQUE INDEX users_display_name_idx
ON users (display_name);The users_email_unique object is a constraint. PostgreSQL creates an underlying unique index to enforce it. The second object is only an index with uniqueness behavior. Prefer a constraint when uniqueness is part of the data model. Create a unique index directly when you need index-specific features, such as a partial or expression index.
| Definition | Main purpose | Typical use |
|---|---|---|
| `UNIQUE` constraint | Declare an integrity rule | Email or external identifier |
| Unique index | Enforce uniqueness and support lookup | Specialized indexing |
| `PRIMARY KEY` | Uniqueness plus row identity | The table’s main identifier |
Single-column and composite uniqueness
A single-column constraint prevents two rows from having the same value. A composite constraint prevents duplicate combinations, not duplicate values in each individual column.
CREATE TABLE memberships (
organization_id bigint NOT NULL,
user_id bigint NOT NULL,
role text NOT NULL,
CONSTRAINT memberships_one_row_per_user
UNIQUE (organization_id, user_id)
);
INSERT INTO memberships VALUES (10, 7, 'member');
INSERT INTO memberships VALUES (10, 8, 'admin');
-- This fails: (10, 7) already exists.
INSERT INTO memberships VALUES (10, 7, 'admin');The pair (organization_id, user_id) is unique. A user can belong to several organizations, and an organization can contain several users.
The column order matters for the supporting index’s lookup performance. A unique constraint on (organization_id, user_id) efficiently supports searches that begin with organization_id, such as all users in organization 10. It is not equally useful for searching only by user_id.
Null values and uniqueness
In PostgreSQL, ordinary unique constraints treat NULL values as distinct. Multiple rows can therefore contain NULL in a unique column.
CREATE TABLE invitations (
invitation_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
accepted_at timestamptz,
token text UNIQUE
);
INSERT INTO invitations (token) VALUES (NULL);
INSERT INTO invitations (token) VALUES (NULL);Both inserts succeed. A NULL means “unknown” or “not present,” so it does not equal another NULL. Add NOT NULL when every row must have a value. In PostgreSQL 15 and later, UNIQUE NULLS NOT DISTINCT (token) can instead make nulls conflict.
Primary keys and foreign keys
A primary key is a special constraint: it is unique, cannot be null, and identifies rows. A table has one primary key, but it can have several unique constraints.
A foreign key can reference a primary key or a suitable unique constraint. This lets another table refer to a value that the database guarantees is unique.
Choosing the rule
Use a primary key for row identity. Use a unique constraint for a required business rule. Use a direct unique index for specialized access patterns, such as a partial rule that applies only to some rows. Test duplicate inserts and null behavior in your database version.
Exercise
Should a table use a unique constraint or a normal index for an email column that must never repeat?
Show answer
Use a UNIQUE constraint and usually also NOT NULL. The constraint states and enforces the data rule, while PostgreSQL uses a unique index to support enforcement and lookups.