Skip to content
We areTOP 1%

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

EasyConceptKeys & Constraints
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

Both prevent duplicate values, but a table can have only one primary key and its columns can never be NULL, while a table can have many unique keys and their columns usually accept NULL.

  • The primary key is the identity of each row and is what foreign keys normally reference.
  • A unique key protects another business rule, such as one account per email address.
  • NULL handling differs: MySQL, PostgreSQL and Oracle allow several NULLs in a unique column, while SQL Server allows only one.
  • Both create an index automatically. In MySQL InnoDB, the primary key is also the clustered index that orders the rows on disk.

Example:

CREATE TABLE users (
  id    INT PRIMARY KEY,       -- one per table, never NULL
  email VARCHAR(100) UNIQUE,   -- a table may have several unique keys
  phone VARCHAR(15) UNIQUE
);
INSERT INTO users VALUES (1, 'a@x.com', NULL);
INSERT INTO users VALUES (2, 'b@x.com', NULL);  -- allowed in MySQL and PostgreSQL
INSERT INTO users VALUES (2, 'c@x.com', '98');  -- fails: duplicate id

More in Keys & Constraints

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account