What is the difference between a primary key and a unique key?
EasyConceptKeys & Constraints
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.
NULLhandling differs: MySQL, PostgreSQL and Oracle allow severalNULLs 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
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What are super, candidate, primary, alternate and composite keys? | Concept | Easy | Read the answer to What are super, candidate, primary, alternate and composite keys? | |||
| 2 | What is the difference between a primary key and a unique key? | Concept | Easy | Read the answer to What is the difference between a primary key and a unique key? | |||
| 3 | What are integrity constraints in DBMS? | Concept | Easy | Read the answer to What are integrity constraints in DBMS? | |||
| 4 | What is a foreign key, and what do ON DELETE CASCADE and ON DELETE SET NULL do? | Concept | Medium | Read the answer to What is a foreign key, and what do ON DELETE CASCADE and ON DELETE SET NULL do? |