SQL · Queries that survive scale

How do UNIQUE constraints work and what are the edge cases?

Mediumunique constraintsindexesnullsUpdated Oct 2026
Quiz this track

Short answer

A UNIQUE constraint prevents duplicate values and is usually enforced by a unique index. Many databases allow multiple NULLs because NULLs are not considered equal.

Uniqueness can be declared at column level or as a table-level constraint over several columns. The database enforces it with a unique index, which also speeds up lookups. The constraint and the index are related but not identical concepts.

sql
CREATE TABLE memberships (
  user_id BIGINT NOT NULL,
  team_id BIGINT NOT NULL,
  role TEXT NOT NULL,
  UNIQUE (user_id, team_id)
);
The composite constraint allows one membership per user and team pair.

Edge cases

  • PostgreSQL and many other engines allow multiple NULLs in a unique column by default
  • PostgreSQL 15+ supports NULLS NOT DISTINCT when one NULL is enough
  • A composite unique constraint only prevents duplicates of the full combination
  • Concurrent inserts can both pass a pre-check, so rely on the constraint rather than SELECT then INSERT
  • A unique index can also support query performance, not only integrity

If the business rule is at most one active record per user, a partial unique index can enforce it. For example, a unique index on user_id where revoked_at IS NULL prevents multiple active subscriptions without blocking historical rows.

Do not implement uniqueness with an application check alone. Two concurrent requests can both see no existing row and insert duplicates unless the database constraint stops them.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Can a UNIQUE column contain multiple NULLs?
  2. 2How do you enforce uniqueness only for active rows?
  3. 3What is the difference between a unique constraint and a unique index?
  4. 4Why is SELECT then INSERT unsafe for uniqueness?

Say it in the interview

A UNIQUE constraint prevents duplicate values and is backed by a unique index. It can cover one column or a combination of columns. The main edge case is NULL, because many databases treat NULLs as distinct and allow several of them. I rely on the database constraint for concurrency safety and use partial unique indexes for rules that apply only to active rows.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.