Sub topic 8
Enforcing uniqueness on a subset of rows
This chapter assumes you can read basic EXPLAIN output and that you know what a UNIQUE constraint does. It also assumes you have met partial indexes, which are B-tree indexes with a WHERE clause. Here you combine the two to enforce uniqueness over only some rows of a table.
All examples use the users table from the running schema:
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
deleted_at timestamptz
);The problem: soft deletes and unique values
Many applications never remove rows. They set deleted_at to a timestamp instead, which is called a soft delete. This keeps history, but it conflicts with a plain unique rule on email.
Suppose you try this:
ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email);Ada signs up with [email protected], deletes her account (the row stays, with deleted_at set), and later signs up again. The second insert fails, because the soft-deleted row still holds the email. Dropping uniqueness entirely would let two active accounts share an email, which is worse.
What you want is "no two active users share an email". Deleted rows should be ignored by the rule.
The unique partial index
A unique index can have a WHERE predicate. PostgreSQL then enforces uniqueness only among the rows that satisfy the predicate.
CREATE UNIQUE INDEX users_active_email_key
ON users (email)
WHERE deleted_at IS NULL;Rows with deleted_at set are not in the index at all. They cannot conflict with anything, and they do not take up space in it.
Now test the behavior:
INSERT INTO users (email) VALUES ('[email protected]'); -- succeeds
INSERT INTO users (email) VALUES ('[email protected]'); -- fails: duplicate key
UPDATE users SET deleted_at = now()
WHERE email = '[email protected]'; -- row leaves the index
INSERT INTO users (email) VALUES ('[email protected]'); -- succeeds againThe first duplicate insert fails with an error like duplicate key value violates unique constraint "users_active_email_key". After the soft delete, the old row no longer counts, so the new insert goes through.
The diagram shows a point that is easy to miss. Restoring a deleted user puts the row back into the index. If another active user has taken that email in the meantime, the restoring UPDATE fails with a unique violation. Your application should handle that case.
What the index does and does not guarantee
The index enforces this rule: among rows where deleted_at IS NULL, no two rows have equal email values. Keep these details in mind.
- Case matters.
[email protected]and[email protected]are different values for atextcolumn. Two active users can differ only by case. To block that, index an expression, as in the next chapter's topic:CREATE UNIQUE INDEX ... ON users (lower(email)) WHERE deleted_at IS NULL. - NULLs are distinct. A unique index treats
NULLvalues as not equal to each other. HereemailisNOT NULL, so this does not matter. On a nullable column, many rows withNULLwould all be allowed unless you declareNULLS NOT DISTINCT(PostgreSQL 15 and later). - The rule is only as strong as the predicate. If a row can be "active" in a way the predicate does not capture, the rule does not cover it.
Partial unique indexes versus constraints
A UNIQUE table constraint cannot have a WHERE clause. Only the index form can. That has a few consequences.
| Feature | `UNIQUE` constraint | `CREATE UNIQUE INDEX ... WHERE` |
|---|---|---|
| Can enforce uniqueness on a subset | No | Yes |
| Shows up as a constraint in `\d` and catalogs | Yes | Only as an index |
| Can be the target of a foreign key | Yes | No |
| Works with `ON CONFLICT (column)` | Yes | Yes, with a matching predicate |
If another table must reference users(email) through a foreign key, you need a full unique constraint, and a partial index cannot serve. For "unique among active rows" rules, the partial index is the right tool.
Using ON CONFLICT with a partial unique index
INSERT ... ON CONFLICT can target a partial unique index, but you must repeat the predicate so PostgreSQL can infer which index you mean:
INSERT INTO users (email)
VALUES ('[email protected]')
ON CONFLICT (email) WHERE deleted_at IS NULL
DO NOTHING;Without the WHERE deleted_at IS NULL part, PostgreSQL looks for an index on email that applies to all rows. It finds none and raises an error: there is no unique or exclusion constraint matching the ON CONFLICT specification.
The predicate in ON CONFLICT must imply the index predicate. Repeating it exactly is the safest choice.
Does the index also speed up queries?
Yes, when a query's conditions imply the index predicate. This is the same matching rule you saw for ordinary partial indexes.
EXPLAIN
SELECT id FROM users
WHERE email = '[email protected]'
AND deleted_at IS NULL;The planner can use users_active_email_key here, because deleted_at IS NULL in the query matches the index predicate. A lookup that omits that condition cannot use it:
EXPLAIN
SELECT id FROM users
WHERE email = '[email protected]';This query could return soft-deleted rows, which are missing from the index, so the planner must choose another plan. If you run lookups like this often, either add deleted_at IS NULL to the query (usually what you mean anyway) or create a second, full index on email. The second option gives up some of the size benefit.
Concurrency and race conditions
Uniqueness checks happen inside the index, so they hold under concurrent writes. If two transactions insert the same active email at the same moment, one waits for the other. When the first commits, the second fails with a unique violation. When the first rolls back, the second succeeds.
This is the main reason to prefer a unique index over a check like this in application code:
-- Unsafe as the only protection:
SELECT 1 FROM users WHERE email = '[email protected]' AND deleted_at IS NULL;
-- ...then INSERT if no row was foundBetween the SELECT and the INSERT, another session can insert the same email. The index closes that gap. You can keep the application check to give friendlier error messages, but the index is the real guarantee.
Common errors and how to avoid them
- Building on data that already violates the rule.
CREATE UNIQUE INDEXfails if existing active rows contain duplicates. Find them first:
``sql SELECT email, count(*) FROM users WHERE deleted_at IS NULL GROUP BY email HAVING count(*) > 1; ``
- Forgetting the predicate in
ON CONFLICT. See above. The error message mentions the specification, not the predicate, so it is easy to misread. - Using a non-immutable function in the predicate. A predicate such as
WHERE deleted_at > now() - interval '30 days'is rejected, becausenow()is not immutable. The index would need to change as time passes. Predicates should depend only on the row's own columns and on immutable functions. - Expecting restores to always work. Reactivating a row can collide with a newer active row, as the state diagram shows.
- Building on a busy table without care. A plain
CREATE UNIQUE INDEXblocks writes while it builds. On a live table useCREATE UNIQUE INDEX CONCURRENTLY. If a concurrent build fails, for example because it finds duplicates, it leaves an invalid index behind that you must drop before retrying:
``sql CREATE UNIQUE INDEX CONCURRENTLY users_active_email_key ON users (email) WHERE deleted_at IS NULL; ``
Check for leftovers with SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;.
Other uses of the same pattern
The pattern "unique among rows matching a condition" applies beyond soft deletes:
- One default per owner.
CREATE UNIQUE INDEX one_default_per_user ON addresses (user_id) WHERE is_default;allows many addresses per user but only one marked default. - One open item per key.
CREATE UNIQUE INDEX one_open_ticket ON tickets (customer_id) WHERE status = 'open';allows a customer only one open ticket at a time. - Unique among non-archived rows. The same shape as the soft-delete case, with an
archivedflag.
In each case the indexed column set is the key you want unique, and the predicate selects the rows the rule applies to.
Exercise
The orders table has a status column. You want to allow at most one order per customer with status 'pending', while any number of orders can have other statuses. Write the statement, then say what happens when you insert two pending orders for the same customer.
Show answer
CREATE UNIQUE INDEX ordersonependingpercustomerkey ON orders (customerid) WHERE status = 'pending'; The first pending order for a customer succeeds. A second pending order for the same customer fails with a duplicate key error, because both rows are in the index and share a customer_id. Orders with other statuses are not in the index, so they never conflict. If the pending order is updated to another status, it leaves the index, and a new pending order is then allowed.
Exercise
Why does INSERT INTO users (email) VALUES ('[email protected]') ON CONFLICT (email) DO NOTHING; fail when the only unique index on email is users_active_email_key, and how do you fix it?
Show answer
The index is partial, so PostgreSQL cannot infer it from ON CONFLICT (email) alone. It reports that no unique or exclusion constraint matches the specification. Fix it by repeating the index predicate: ON CONFLICT (email) WHERE deleted_at IS NULL DO NOTHING.