Skip to the solution
EasyDSA12 min read

What is the difference between a primary key and a unique constraint?

1.1k views

The problem

Question presented to candidate: "Our users table has an id primary key, but email and username must also be unique. Both a primary key and a unique constraint stop duplicates, so what is actually different about them, and how do you decide which column gets which?"

What a strong answer should cover:

  • Both reject duplicate values and both are backed by a unique index
  • A table has at most one primary key but any number of unique constraints
  • The primary key is always NOT NULL; a unique column allows NULL, and by default several NULLs, because NULL is not equal to NULL
  • Engine differences: PostgreSQL 15+ NULLS NOT DISTINCT, SQL Server allowing only one NULL, SQLite letting NULL into some primary keys
  • The primary key is the identity other tables reference (a foreign key can also target a unique key), and in MySQL InnoDB it is the clustered index
  • Typical design: a stable surrogate primary key plus unique constraints on natural keys like email

Code / implementation expected: Optional β€” a table with one PRIMARY KEY and two UNIQUE columns, showing the NULL behaviour.

Schema used by the examples:

  • constraints

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 9 sections

Run the code

Edit the query and run it against the tables for this question.

SQLA UNIQUE column holds several NULLs: unique means unique among the values that exist
SQLSQLite: each UNIQUE constraint creates its own index; INTEGER PRIMARY KEY needs none
SQLA foreign key may target a UNIQUE column, not only the primary key
PostgreSQL: the catalog shows one constraint of type p and three of type u, and the primary key column became NOT NULL
SELECT c.conname, c.contype, a.attname, a.attnotnull
FROM pg_constraint AS c
JOIN pg_attribute AS a ON a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey)
WHERE c.conrelid = 'users'::regclass
ORDER BY c.contype, c.conname;

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 2 of 82 in SQL

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All SQL questions
Up nextEasy

What is the logical order of execution of a SQL query?

Continue