Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is the difference between a UNIQUE constraint and a unique index in PostgreSQL? How are NULLs treated, and how does PostgreSQL 15+ let you change that?

A UNIQUE constraint is a logical rule in the schema, and PostgreSQL implements it with a unique B-tree index. A unique index created directly enforces the same rule but can also be partial or on an expression, which a constraint cannot express. Foreign keys can reference either a unique constraint or a non-partial unique index. By default NULLs are treated as distinct, so many rows may have NULL in a unique column; since PostgreSQL 15, UNIQUE NULLS NOT DISTINCT treats NULLs as equal.

Why this question is asked

Uniqueness is one of the most important guarantees a database gives an application: one account per email, one active subscription per customer, one invoice number per year. The difference between a constraint and an index sounds academic until we need a rule like 'unique among rows that are not deleted', or until NULLs let duplicates through. Interviewers ask this to check that we understand both the mechanism and its edge cases. In this answer, we will recap what each one is, see what only an index can express, look at foreign keys, explain NULL handling and the PostgreSQL 15 option, and build the soft-delete pattern.

1A Quick Recap of Constraints and Indexes

A constraint is a rule the database guarantees about the data, declared as part of the table: NOT NULL, CHECK, PRIMARY KEY, UNIQUE, FOREIGN KEY. An index is a physical structure that speeds up lookups. They meet in uniqueness: to check that a new value is unique, the database needs a fast way to look for an existing equal value, and that is an index.

So when we declare a UNIQUE constraint, PostgreSQL creates a unique B-tree index with the constraint's name to enforce it. The constraint appears in pg_constraint and in information_schema; the index appears in pg_index. When we create a unique index directly, there is an index and no constraint entry, but the uniqueness is enforced in exactly the same way.

SQL
ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email);
-- creates index users_email_key, and a constraint in pg_constraint
CREATE UNIQUE INDEX users_username_idx ON users (username);
-- creates only an index; duplicates are rejected all the same
INSERT INTO users (email, username) VALUES ('a@x.io', 'ann'); -- INSERT 0 1
INSERT INTO users (email, username) VALUES ('b@x.io', 'ann');
-- ERROR: duplicate key value violates unique constraint "users_username_idx"

2What Only a Unique Index Can Express

A UNIQUE constraint lists plain columns and applies to every row. A unique index is more flexible: it can be partial, with a WHERE clause, so uniqueness applies only to some rows, and it can be on an expression, such as lower(email), so uniqueness applies to a computed value. Neither can be written as a table constraint in PostgreSQL. Constraints, on the other hand, have features indexes lack: they can be DEFERRABLE, checked at commit instead of per statement, and they are what information_schema and many tools understand.

UNIQUE constraint vs unique index in PostgreSQL
FeatureUNIQUE constraintUnique index
Enforced bya unique B-tree indexitself
Partial (WHERE ...)noyes
On an expression, e.g. lower(email)noyes
DEFERRABLEyesno
Target of a foreign keyyesyes, if not partial
ON CONFLICT targetyes, by name or columnsyes, by columns or expression

3Foreign Keys and Uniqueness

A foreign key must reference columns that are guaranteed unique, so each child row points to exactly one parent. PostgreSQL accepts a primary key, a unique constraint, or a unique index that is not partial on those exact columns. A partial unique index does not qualify, because it only guarantees uniqueness for some rows, and an expression index does not qualify, because the foreign key compares plain column values.

4How NULLs Are Treated

In SQL, NULL means unknown, and NULL = NULL is not true, it is unknown. Following that logic, a unique index treats NULLs as distinct from each other by default, so any number of rows may have NULL in a unique column. That is often what we want: many users without a phone number, each with phone NULL. But sometimes it lets real duplicates in, for example a uniqueness rule on (tenant_id, external_id) where external_id is optional and two rows with the same tenant and NULL should be considered the same.

SQL
CREATE TABLE devices (tenant_id int, serial text, UNIQUE (tenant_id, serial));
INSERT INTO devices VALUES (1, NULL); -- INSERT 0 1
INSERT INTO devices VALUES (1, NULL); -- INSERT 0 1 NULLs are distinct
CREATE TABLE devices2 (tenant_id int, serial text, UNIQUE NULLS NOT DISTINCT (tenant_id, serial));
INSERT INTO devices2 VALUES (1, NULL); -- INSERT 0 1
INSERT INTO devices2 VALUES (1, NULL);
-- ERROR: duplicate key value violates unique constraint "devices2_tenant_id_serial_key"

PostgreSQL 15 added NULLS NOT DISTINCT for unique constraints and unique indexes, which treats NULLs as equal for the uniqueness check. Before version 15, the usual workaround was a second, partial unique index on tenant_id WHERE serial IS NULL, or an expression index on coalesce(serial, '').

5The Soft-Delete Pattern With a Partial Unique Index

Many applications soft-delete rows by setting deleted_at instead of removing them. A plain unique constraint on email would then block a person from signing up again after deleting their account, because the old row still holds the email. A partial unique index enforces uniqueness only among live rows.

SQL
CREATE UNIQUE INDEX users_email_live_idx ON users (lower(email)) WHERE deleted_at IS NULL;
INSERT INTO users (email) VALUES ('ann@x.io'); -- ok
UPDATE users SET deleted_at = now() WHERE email = 'ann@x.io'; -- soft delete
INSERT INTO users (email) VALUES ('Ann@x.io'); -- ok, old row is deleted
INSERT INTO users (email) VALUES ('ann@X.io');
-- ERROR: duplicate key value violates unique constraint "users_email_live_idx"

Notice that this index combines both features only an index has: it is partial and on an expression. That is exactly why PostgreSQL offers unique indexes beyond constraints.

6Follow-up questions

How does MySQL treat NULLs in unique indexes?

InnoDB also treats NULLs as distinct in a unique index, so multiple rows with NULL in a unique column are allowed, which matches the SQL standard's usual reading. MySQL has no NULLS NOT DISTINCT option and no partial indexes, so to make NULL count as a value we typically use a generated column that maps NULL to a sentinel, such as coalesce(serial, ''), and put the unique index on that, or declare the column NOT NULL with a default. In MySQL, a UNIQUE constraint and a unique index are essentially the same thing.

Should I prefer a constraint or an index when both work?

When a plain column list is enough, a named UNIQUE constraint is usually nicer: it documents intent in the schema, tools and ORMs understand it, and it can be deferred. When we need a partial or expression rule, we use a unique index and give it a clear name, because the name appears in error messages that our code may need to recognise.

7Conclusion

In this answer, we saw that a UNIQUE constraint is a logical rule that PostgreSQL enforces with a unique B-tree index, while a unique index created directly can also be partial or on an expression, and a constraint can be deferrable. Foreign keys can reference a unique constraint or a non-partial unique index. NULLs are distinct by default, so many NULLs are allowed, and PostgreSQL 15 added NULLS NOT DISTINCT to treat them as equal. Finally, a partial unique index such as one on lower(email) WHERE deleted_at IS NULL supports soft deletes.

What to say in the interviewAbout 90 seconds aloud

Open with

In PostgreSQL a UNIQUE constraint is a rule declared on the table, and it is implemented by a unique B-tree index that the database creates for it. A unique index created directly enforces uniqueness in exactly the same way, but it can do two things a constraint cannot: it can be partial, with a WHERE clause, and it can be on an expression like lower of email.

Then, if they want more

A constraint, on the other hand, can be deferrable and is what tools and information_schema understand. A foreign key can reference a primary key, a unique constraint, or a unique index that is not partial on those columns.

For NULLs, the default follows SQL's idea that NULL is unknown, so NULLs are distinct and any number of rows can have NULL in a unique column. Since PostgreSQL 15, we can write UNIQUE NULLS NOT DISTINCT so that NULLs count as equal, which is useful for composite rules like tenant and optional external id.

Before 15 the workaround was an extra partial index or a coalesce expression. A practical pattern that needs the index form is soft delete: a unique index on lower of email WHERE deleted_at IS NULL, so only live accounts must be unique and a person can sign up again after deleting their account.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 15
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is the difference between a UNIQUE constraint and a unique index in PostgreSQL? How...": https://scrivio-interview-library.netlify.app/databases/indexing/a091dd2f69/