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: