Primary Key vs Unique key — SQL Technical Interview Questions & Answers

Primary Key vs Unique key

Primary Key vs Unique key

  • Both unique. PK: one per table, NOT NULL, clustered in InnoDB. UNIQUE: many allowed, NULL handling differs, secondary index.
  • id INT PRIMARY KEY, email VARCHAR UNIQUE is the classic pair.
  • Trap: two PRIMARY KEYs. Impossible. Two UNIQUE keys. Fine.
  • On the example next to this theory: Primary Key vs Unique key — keys and constraints protect data integrity; indexes speed lookups.

Technical Interview Tip: One PK. Many UNIQUE (email, phone).

Code Examples for Primary Key vs Unique key

Primary Key vs Unique key — sample query

CREATE TABLE authors (
  id INTEGER PRIMARY KEY,
  email TEXT UNIQUE NOT NULL
);
CREATE TABLE books (
  id INTEGER PRIMARY KEY,
  author_id INTEGER NOT NULL,
  title TEXT NOT NULL,
  FOREIGN KEY (author_id) REFERENCES authors(id)
);
INSERT INTO authors VALUES (1, 'a@x.com');
INSERT INTO books VALUES (1, 1, 'SQL Basics');
SELECT * FROM books;

Primary Key vs Unique key — keys and constraints protect data integrity; indexes speed lookups.

How to Explain Primary Key vs Unique key to an Interviewer

Can a table have two PRIMARY KEYs?

No It can have many UNIQUE keys