Primary Key vs Foreign Key — SQL Technical Interview Questions & Answers
Primary Key vs Foreign Key
Primary Key vs Foreign Key
- PRIMARY KEY is this table’s identity (students.roll). FOREIGN KEY is a pointer in another table (marks.roll) that must match a parent PK/UNIQUE. Parent first, then child.
- You can query without declaring an FK, but then the database will not stop orphans. Declare the FK.
- Trap: putting the FK on the parent instead of the child.
- On the example next to this theory: Primary Key vs Foreign Key — keys and constraints protect data integrity; indexes speed lookups.
Technical Interview Tip: students.roll PK. marks.roll FK → students.roll.
Code Examples for Primary Key vs Foreign Key
Primary Key vs Foreign 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 Foreign Key — keys and constraints protect data integrity; indexes speed lookups.
How to Explain Primary Key vs Foreign Key to an Interviewer
Where do you put the FOREIGN KEY?
On the child table Points at parent PK