In a relational database, what's the difference between a primary key and a foreign key, and what does referential integrity give you?

technical-conceptual · Junior level · software-engineering

What the interviewer is really asking

Assesses whether the candidate understands how relational tables are linked and how the database enforces consistency across those links, which underpins almost every schema they'll touch.

What to say

What to avoid

Example answers

Strong: A primary key uniquely identifies each row — it's unique and non-null, like an id column. A foreign key is a column that references another table's primary key, which is how you link rows: an orders table with a customer_id foreign key pointing at customers(id). Referential integrity is the database enforcing that link — it won't let me insert an order with a customer_id that doesn't exist, and if I try to delete a customer who still has orders, it either blocks me or cascades the delete depending on how I set up the constraint. So I can't end up with orphaned orders pointing at a customer who's gone, and the error shows up at write time instead of corrupting a report later.

Weak: A primary key is the main key of the table and a foreign key is a key from a foreign table. They both make the row unique. Referential integrity just means the data is correct and the keys match up. I usually let the application handle making sure the references are valid.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.