Q18. What is the difference between a primary key and a unique constraint?
Both enforce uniqueness and both get an index automatically. A table has exactly one primary key, its columns can never be NULL, and it's the default target for foreign keys. Unique constraints can appear many times per table and allow NULLs, which the standard treats as distinct from each other.
The mental model: the primary key is the row's identity; unique constraints guard alternate keys like email or national ID that must not repeat but aren't the identity.
| Primary key | Unique constraint | |
|---|---|---|
| Per table | Exactly one | Any number |
| NULLs allowed | Never | Yes (treated as distinct) |
| Foreign key target | Default choice | Allowed, less common |
| Purpose | Row identity | Alternate keys (email, SKU) |
Key point: The NULL difference is the discriminator the key signal is. Bonus depth: PostgreSQL 15 added NULLS NOT DISTINCT for unique constraints.