Sub topic 11
Unique Indexes and Constraints
This chapter assumes you know basic SQL, how a B-tree index finds rows, and the difference between a table and an index. Examples use PostgreSQL syntax. Differences in other databases are noted where they matter.
Why uniqueness belongs in the database
An application can check "does this email already exist?" before inserting. Two concurrent requests can both run that check, both see no match, and both insert. The result is a duplicate. Only the database sees every write, so only it can enforce uniqueness reliably.
A unique index is the mechanism. It is a B-tree index with one extra rule: no two entries may have the same key. Every insert or update must search the index for the new key. If a matching entry exists, the statement fails with an error. The search is the same logarithmic descent you saw in the B-tree chapter, so the check costs little.
This gives a unique index two jobs. It speeds up lookups on the column, like any index. It also rejects duplicates.
Constraints versus indexes
A constraint is a rule about data. An index is a data structure. They are different things, but in most databases a uniqueness constraint is implemented by a unique index.
CREATE TABLE users (
id bigint PRIMARY KEY,
email text NOT NULL,
handle text NOT NULL,
CONSTRAINT users_email_key UNIQUE (email)
);
CREATE UNIQUE INDEX users_handle_idx ON users (handle);Both statements produce a unique B-tree. The first declares a constraint, and PostgreSQL creates the backing index for you. The second creates only an index. The practical differences are small:
| Aspect | `UNIQUE` constraint | `CREATE UNIQUE INDEX` |
|---|---|---|
| Appears in catalog as a constraint | Yes | No |
| Can be the target of a foreign key | Yes | Only if it is also a constraint (in PostgreSQL, a unique index alone cannot be referenced) |
| Can be partial or use expressions | No | Yes |
| Dropped with | `ALTER TABLE ... DROP CONSTRAINT` | `DROP INDEX` |
Prefer the constraint when uniqueness is a business rule that other tables depend on. Use a plain unique index when you need a partial or expression form, covered later in this chapter.
Primary keys
A primary key is a unique constraint plus NOT NULL. Declaring id bigint PRIMARY KEY creates a unique B-tree index on id automatically. You do not need to create another index on that column. A second index on the same column only adds write cost.
A table can have only one primary key but any number of unique constraints. In InnoDB (MySQL), the primary key index is also the clustered index, so the table's rows are stored inside it. In PostgreSQL, the primary key index is a secondary index like any other, and rows live in a separate heap. The previous chapter on clustered and secondary indexes covers that difference.
Foreign keys do not create indexes
A foreign key requires the referenced column to be unique. It does not index the referencing column. Consider:
CREATE TABLE orders (
id bigint PRIMARY KEY,
user_id bigint NOT NULL REFERENCES users (id),
created_at timestamptz NOT NULL
);users.id is indexed because it is a primary key. orders.user_id is not indexed in PostgreSQL. Two things then become slow. Joins from users to their orders scan the orders table. Deleting a user forces the database to scan orders to check for referencing rows. MySQL's InnoDB creates an index on the referencing column automatically, which is one reason people carry the wrong assumption between systems.
CREATE INDEX orders_user_id_idx ON orders (user_id);NULL and uniqueness
The SQL standard says NULL means "unknown", so two NULL values are not considered equal. PostgreSQL follows this: a unique index allows any number of rows with NULL in the indexed column.
CREATE TABLE accounts (
id bigint PRIMARY KEY,
phone text,
CONSTRAINT accounts_phone_key UNIQUE (phone)
);
INSERT INTO accounts VALUES (1, NULL);
INSERT INTO accounts VALUES (2, NULL); -- succeeds
INSERT INTO accounts VALUES (3, '555-0100');
INSERT INTO accounts VALUES (4, '555-0100'); -- fails: duplicate keyThis is usually what you want for optional fields. If you want at most one NULL, behavior varies by database:
- PostgreSQL 15 and later accepts
UNIQUE NULLS NOT DISTINCT, which treatsNULLvalues as equal. - SQL Server treats
NULLas a value in a unique index, so it allows only one. - MySQL and Oracle's behavior differs again for single and composite keys, so check your version's documentation before relying on it.
For composite unique indexes, a row is exempt from the check if any key column is NULL (under the default PostgreSQL behavior). The pair (1, NULL) can appear many times.
Composite uniqueness
A unique index over several columns enforces uniqueness of the combination, not of each column.
CREATE TABLE memberships (
user_id bigint NOT NULL,
team_id bigint NOT NULL,
role text NOT NULL,
UNIQUE (user_id, team_id)
);A user can join many teams and a team can have many users, but each pair appears once. The leftmost-prefix rule still applies to the index. Queries filtering on user_id alone can use it. Queries filtering only on team_id cannot seek efficiently, so you may need a second, non-unique index on team_id.
Column order in a unique index does not change which rows are rejected. It only changes which queries benefit, so pick the order that serves your most common lookup.
Partial unique indexes
A partial unique index enforces uniqueness only among rows that match a condition. This models rules such as "a user can have only one active subscription, but any number of cancelled ones."
CREATE UNIQUE INDEX subscriptions_one_active_idx
ON subscriptions (user_id)
WHERE status = 'active';Rows with other statuses are not in the index, so they cannot conflict. The same technique implements soft-delete uniqueness:
CREATE UNIQUE INDEX users_email_live_idx
ON users (lower(email))
WHERE deleted_at IS NULL;This index also uses an expression, lower(email), so [email protected] and [email protected] count as duplicates. Queries that want to use the index for lookups must repeat the same expression and, for the partial condition, include a predicate the planner can prove implies deleted_at IS NULL.
Handling conflicts on insert
Because the database rejects duplicates, you can use that to your advantage. Instead of checking first and inserting second, insert and handle the conflict.
INSERT INTO users (id, email, handle)
VALUES (10, '[email protected]', 'ada')
ON CONFLICT (email) DO NOTHING;
INSERT INTO users (id, email, handle)
VALUES (10, '[email protected]', 'ada')
ON CONFLICT (email) DO UPDATE SET handle = EXCLUDED.handle;ON CONFLICT requires a unique index or constraint that matches the named columns. This pattern is atomic. There is no gap between check and write for another session to slip into. MySQL spells it INSERT ... ON DUPLICATE KEY UPDATE, and the SQL standard form is MERGE.
What happens under concurrency
Suppose two sessions insert the same email at once. Session A inserts its index entry first. Session B reaches the same key and finds an entry that belongs to a transaction that has not yet committed. B waits. If A commits, B fails with a unique violation. If A rolls back, B proceeds. This waiting is correct behavior, but it means long-running transactions that insert unique keys can block other writers of the same key.
Two further points:
- Unique checks are not deferred by default. A statement that temporarily creates a duplicate, such as
UPDATE t SET n = n + 1over a unique column, can fail depending on row processing order. PostgreSQL supportsDEFERRABLEconstraints that check at commit, but unique indexes created withCREATE UNIQUE INDEXcannot be deferred. Only the constraint form can. - Failed inserts still consume sequence values and can leave dead index entries behind, which vacuum later reclaims.
Adding uniqueness to an existing table
Creating a unique index on a large table can fail if duplicates already exist, and it blocks writes while it builds. To find existing duplicates first:
SELECT email, count(*)
FROM users
GROUP BY email
HAVING count(*) > 1;After cleaning the data, build the index without blocking writes:
CREATE UNIQUE INDEX CONCURRENTLY users_email_uidx ON users (email);
ALTER TABLE users
ADD CONSTRAINT users_email_key UNIQUE USING INDEX users_email_uidx;If a concurrent build fails, PostgreSQL leaves an INVALID index behind. It still slows writes, so drop it and retry.
Cost summary
A unique index has the write costs of any B-tree index, plus a search on every insert and update of the key. In return you get correctness that no application code can guarantee. Treat unique indexes as part of your data model first and a performance feature second.
Exercise
A table invites(id, team_id, email, accepted_at) must allow many accepted invites per email, but only one pending invite (where accepted_at IS NULL) per team and email. Write the index that enforces this, and say why a plain UNIQUE (team_id, email) constraint is wrong.
Show answer
CREATE UNIQUE INDEX invitesonependingidx ON invites (teamid, email) WHERE acceptedat IS NULL; A plain UNIQUE (teamid, email) would also forbid a second invite to the same email after the first was accepted, because accepted rows would still be in the index and conflict. The partial index contains only pending rows, so accepted rows never collide.
Exercise
In PostgreSQL, a table has phone text UNIQUE. You insert three rows with phone = NULL. How many succeed, and how would you change the definition to allow only one?
Show answer
All three succeed, because NULL values are not considered equal for uniqueness. In PostgreSQL 15 or later, declare phone text UNIQUE NULLS NOT DISTINCT. On older versions, create a partial or expression unique index, for example a unique index on (coalesce(phone, '')), after confirming that the empty string is not a valid value.