Primary Key — SQL Technical Interview Questions & Answers

Primary Key

Primary Key

  • PRIMARY KEY uniquely identifies each row. students.roll or an AUTO_INCREMENT id. Not NULL. Only one PRIMARY KEY per table (it may be two columns together — composite).
  • InnoDB uses the PK as the clustered index — rows are stored in PK order. A stable integer PK is a good default. Don’t use a name as PK (people change names).
  • INSERT duplicate PK → error 1062. Foreign keys from other tables point at this PK.
  • Trap: table with no PK. Trap: VARCHAR UUID PK on a huge table without thinking about InnoDB clustering (advanced, but worth a line if asked).
  • On the example next to this theory: Primary Key — keys and constraints protect data integrity; indexes speed lookups.

Technical Interview Tip: roll INT PRIMARY KEY or id INT PRIMARY KEY AUTO_INCREMENT.

Code Examples for Primary Key

Primary 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 — keys and constraints protect data integrity; indexes speed lookups.

How to Explain Primary Key to an Interviewer

Rules of a PRIMARY KEY?

Unique NOT NULL Only one PK

Duplicate PK?

Error 1062