What is the difference between a primary key and a unique key?
Both prevent duplicate values, but a table can have only one primary key and it can never be NULL, while a table can have many unique keys and they accept NULL.
- Primary key: identifies each row and implies
NOT NULL. In MySQL's InnoDB engine the table data is physically organised by the primary key (the clustered index). - Unique key: enforces uniqueness on other columns such as email or PAN number. In MySQL a unique column can hold multiple NULLs, because one NULL is never equal to another.
- Both automatically create an index.
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
phone VARCHAR(15) UNIQUE
);Interview tip: Expect "can a unique key be NULL?" as the follow-up: in MySQL yes, and several rows can have NULL in that column.