Primary Keys & Foreign Keys
How a database identifies one exact row, and how rows in different tables point to each other.
What is it?
If two customers are both named "Sam Lee," how does the database tell them apart? It needs a column whose value is unique for every row. That column is the primary key, usually an auto-generated id number.
Once every row has a unique id, tables can reference each other. An orders table doesn't copy the user's name and email into every order. It stores the user's id in a column like user_id. That column is a foreign key: it points to a primary key in another table, linking the rows without duplicating data.
Explain like I'm 10
A primary key is like a student ID number: no two students share one, even with the same name. A foreign key is like writing that ID on a library checkout card instead of the student's full name and address. It points back to the one record that has all the details.
Examples
A primary key
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
email TEXT
);PRIMARY KEY tells the database that id uniquely identifies each row. It won't allow two rows with the same id.
A foreign key linking two tables
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
total_cents INTEGER
);
-- orders table:
-- id | user_id | total_cents
-- 1 | 2 | 4599
-- 2 | 2 | 1200
-- 3 | 3 | 800Each order stores only the id of the user who placed it. Orders 1 and 2 both belong to user 2, without repeating that user's name or email.
How it works
The database enforces a primary key itself. It refuses any insert or update that would duplicate a value in that column. Most tables use an auto-incrementing integer id, since it's unique and never changes.
A foreign key is a regular column whose values should match a primary key in another table. Many databases enforce this too, refusing an order whose user_id doesn't exist in users. That keeps the two tables consistent.
Why does it exist?
Without a unique id, you couldn't safely update or delete "this one record." You might match several similar rows by accident.
Without foreign keys, you'd copy full details (name, email, address) into every related table. That wastes space and becomes a mess as soon as the copied data changes.
When to use it
Give almost every table a primary key. It's the basis for updating, deleting, and linking specific rows. Add a foreign key whenever a row "belongs to" or references a row in another table, like an order belonging to a user.
When not to use it
There's rarely a reason to skip a primary key on a real table. You can skip foreign keys for small, throwaway, or deliberately denormalized datasets where the tables don't need to stay in sync.
Common mistakes
Using a real-world value like an email as the primary key, which breaks when a user changes their email.
Skipping the foreign key column and copying a related row's full details everywhere instead.
Thinking a foreign key keeps data in sync on its own. It only links rows; queries still need a join to show combined data.
Practice exercises
- Easy:
Explain why an auto-incrementing id is usually a better primary key than a person's name.
- Medium:
Design a 'comments' table that belongs to both a 'posts' table and a 'users' table (who wrote it, and on which post). Name the foreign key columns you'd add.
- Hard:
Describe what could go wrong if you inserted a comment whose user_id doesn't match any real user.
Interview questions
What is a primary key?
A column (or set of columns) whose value uniquely identifies each row in a table, enforced by the database to never have duplicates.
What is a foreign key?
A column in one table that stores the primary key value of a row in another table, creating a link between the two without duplicating data.
Why use a generated id instead of a real-world value like an email as a primary key?
Real-world values can change over time (like an email being updated), which breaks anything referencing it; a generated id never changes.
What is a composite primary key?
A primary key made of several columns together. The combination must be unique, even though no single column is. For example, order_items could use (order_id, product_id), so a product appears only once per order.
When would you reach for a composite primary key instead of a single auto-incrementing id column?
When a row is fully defined by a combination of foreign keys and nothing else needs to identify it. The classic case is a join table, like order_items linking orders and products, where 'this order plus this product' is the row.
Must a foreign key always reference the other table's primary key specifically?
No. It can reference any column that's guaranteed unique (usually via a UNIQUE constraint). Referencing the primary key is just the most common and simplest case.
What is referential integrity, in plain terms?
The guarantee that every foreign key value matches a real row in the table it references. No order can point at a user_id that doesn't exist.
If a foreign key constraint is enforced, what happens when you try to insert a row whose foreign key value doesn't exist in the referenced table?
The database rejects the insert with a constraint violation error. It won't store a row pointing at a missing record.
What does `ON DELETE CASCADE` do on a foreign key?
When the referenced row (say, a user) is deleted, the database also deletes every row that references it (that user's orders), instead of leaving them pointing at nothing.
What does `ON DELETE SET NULL` do, and what does it require of the foreign key column?
When the referenced row is deleted, referencing rows keep existing but their foreign key is set to NULL. The foreign key column must therefore allow NULL.
What does `ON DELETE RESTRICT` (or the default `NO ACTION` in many databases) do?
It blocks the delete. The database won't delete the referenced row while any other row still references it, so you must deal with those references first.
Running `DELETE FROM users WHERE id = 1;` fails with a foreign key constraint violation. What's the most likely cause?
A row in another table (like orders) still points at that user, and the foreign key uses RESTRICT/NO ACTION (a common default) rather than CASCADE or SET NULL. The database refuses to leave the reference dangling.
Between `ON DELETE CASCADE` and `ON DELETE RESTRICT`, which is generally the safer default, and why?
RESTRICT. It forces you to decide what happens to dependent rows, instead of silently deleting a possibly large chain of related data. CASCADE is powerful but can remove far more than expected when relationships run deep.
Can a primary key column contain `NULL`?
No. A primary key means both unique and NOT NULL. A NULL can't reliably identify a row, and one NULL isn't even equal to another.
Can a foreign key column contain `NULL`, and what does that mean?
Yes, unless it's also marked NOT NULL. A NULL foreign key usually means 'no reference right now', like an order with no assigned sales rep. It's an optional relationship, not a broken one.
What is the difference between a natural key and a surrogate key?
A natural key is a real-world value already unique to the row, like a national ID or email. A surrogate key is an artificial value the database generates just to identify the row, like an auto-incrementing id, with no meaning outside the database.
What's a downside of using a natural key like an email as a primary key, beyond the fact that emails can change?
Natural keys are often longer or more complex than an integer, so they're slower to index and join on. That cost spreads to every table that uses them as a foreign key.
Can a table have more than one column, or combination of columns, that could each serve as a unique identifier? What are those called?
Yes. Each is a candidate key. The table picks one as its primary key; the others can still be enforced with UNIQUE constraints.
What's the difference between a `UNIQUE` constraint and a `PRIMARY KEY` constraint?
Both enforce uniqueness, but a table has only one primary key and can have many UNIQUE constraints. Unlike a primary key, a UNIQUE column can usually hold NULL, often more than once in most databases, since NULL never equals another NULL.
What happens if you try to insert a row whose primary key value already exists in the table?
The database rejects it with a uniqueness violation error. It never silently overwrites or duplicates the existing row.
Design a `comments` table that belongs to both a `posts` table and a `users` table. What foreign key columns would it need?
Two foreign keys: post_id INTEGER REFERENCES posts(id) for the post, and user_id INTEGER REFERENCES users(id) for the author, plus its own primary key, id.
What is a self-referencing foreign key? Give an example.
A foreign key that references the primary key of its own table. For example, employees with manager_id INTEGER REFERENCES employees(id), where a manager is just another employee row.
Given `orders(id PK, user_id FK -> users.id ON DELETE CASCADE)`, what happens to a user's orders if that user's row is deleted?
All orders whose user_id points at that user are deleted too, because of ON DELETE CASCADE.
Given `orders(id PK, assigned_rep_id FK -> employees.id ON DELETE SET NULL)`, what happens to an order if the employee assigned to it is deleted?
The order stays, but its assigned_rep_id is set to NULL, so it's now unassigned.
Does adding a foreign key column automatically combine that table's data with the referenced table's data in query results?
No. A foreign key only creates (and optionally enforces) the link. To see data from both tables in one result, you still write a JOIN.
Why does inserting an order with a `user_id` that doesn't correspond to any real user cause problems, even without an actively enforced foreign key constraint?
Queries joining orders to users find nothing for that row, reports can silently undercount it, and later nobody can tell whether it's a typo or an intentionally orphaned record. Referential integrity exists to prevent exactly this.
In a composite primary key like `(order_id, product_id)`, does the order the two columns are listed in change what's enforced?
No. The combination must be unique either way. But column order can affect which queries can use the underlying index efficiently.
Is it valid, from the database's point of view, to create a table with no primary key at all?
Most databases allow it, but it's rarely wise. Without one, there's no guaranteed way to target, update, or delete one specific row, and other tables can't cleanly reference it.
What's the practical difference between a column that's `NOT NULL` and `UNIQUE` versus that same column being declared `PRIMARY KEY`?
NOT NULL plus UNIQUE enforces the same two rules as a primary key. But a table has only one primary key, marking the main identifier other tables should reference, while it can have many NOT NULL UNIQUE columns.
If `orders` has `ON DELETE CASCADE` back to `users`, and `order_items` has `ON DELETE CASCADE` back to `orders`, what happens when a single user row is deleted?
The user's orders are deleted, and each of those deletes removes that order's order_items. One delete can ripple through several tables when CASCADE is chained, which is why RESTRICT is often the preferred default.