Foreign keys: how tables stay connected
Chapter 4 — “Threads”
QUERY dims the lights in the holopanel hall. The five Kotomarket tables remain in the dark like separate islands: users, products, orders, order_items, events.
He sweeps a paw across the panel, and thin amber threads light up between the tables. One runs from a customer to an order. Another connects an order to the items inside it. A third leads from an item to a product. Now you can see which rows belong together.
QUERY: Metrics have already shown you “what happened.” Now we'll find who it happened to. Your “Relationships” clearance is open. Try not to break anything.

Why data lives in different tables
In the Kotomarket database, data is split across different tables so the same information doesn't have to be repeated in every row.
For example, a customer's name is stored once in the users table:
users
id | full_name
---+----------------
18 | Daniel Johnson
Their orders are stored in a different table, orders:
orders
id | user_id | total_amount
----+---------+-------------
1 | 18 | 59.80
69 | 18 | 299.50
There's no need to repeat the name Daniel Johnson in every row of orders. user_id = 18 is enough: we can use it to find the row in users where id = 18.
A column like this is called a , or FK.
What is a foreign key?
A foreign key is a column in one table that points to a row in another table.
In our example, the relationship looks like this:
orders.user_id → users.id
You can read it like this:
users.idstores the customer's identifier;orders.user_idstores the identifier of the customer who owns the order;- if
orders.user_id = 18, the order belongs to the row whereusers.id = 18.
A foreign key usually stores the id of the related row, rather than a name, email address, or object description.
It's easy to confuse a foreign key with a . users.id is a primary key: every row in users has its own value, the value never repeats, and it can't be empty. orders.user_id is a foreign key: the same value can appear in several orders because one customer can place multiple orders, and the value points to the primary key of another table.
Relationships in the Kotomarket database
Here are the main relationships in our training database:
-
orders.user_id→users.id
one user can place many orders; -
order_items.order_id→orders.id
one order can contain many items; -
order_items.product_id→products.id
one product can appear in many items across different orders; -
events.user_id→users.id
an event can be associated with a user; -
events.product_id→products.id
an event can be associated with a product.
These relationships tell you which columns to compare when joining tables.
For example, to get the customer's name for an order, we join on:
orders.user_id = users.id
To get the product name for an order item:
order_items.product_id = products.id
And to get all the items in a particular order:
order_items.order_id = orders.id
JOIN uses this kind of match: it takes a key value from one table, finds the same value in another, and combines the related data into a single result row.
To remember the idea, picture the threads from the beginning of the chapter:
a foreign key is a thread between tables,
JOINis the command that follows that thread and pulls in the related data.
A (FK) is a column whose values reference a key in another table.
For example, orders.user_id = 18 means the order belongs to the customer with users.id = 18.
A foreign key also protects the data. The database won't let you insert an order with a user_id that doesn't exist in the users table. This is called : every recorded relationship must point to an existing row.
order_items — product_id, quantity, and unit_price.A live wire: what happens when you delete the parent
A keeps the relationship between tables valid by preventing references to rows that don't exist.
Imagine that orders contains orders for the user with user_id = 18. Now someone deletes that user from users:
DELETE FROM users
WHERE id = 18;
What should happen to that user's orders?
They still contain a reference to users.id = 18. If the user is deleted, those orders will point to a row that no longer exists. The database considers this a violation of .
You specify what should happen on deletion when you create the foreign key. For example:
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL REFERENCES users(id) ON DELETE RESTRICT
-- other columns
);
We'll cover the full CREATE TABLE syntax in Chapter 9, “.” For now, you only need to understand two parts of this definition:
REFERENCES users(id)
means that user_id references users.id.
And this part:
ON DELETE RESTRICT
sets how the database responds when someone tries to delete a user that other rows already reference.
Parent and child
Two terms are used for this kind of relationship:
- parent table — the table being referenced;
- child table — the table that contains the foreign key.
Take this relationship:
orders.user_id → users.id
Here, users is the parent table: it contains the user row that the reference points to.
orders is the child table: each order stores the user_id of its user.
ON DELETE options
When a parent row is deleted, the database can handle the related rows in several ways.
| Behavior | What the database does | When to use it |
|---|---|---|
RESTRICT / NO ACTION | Prevents the parent from being deleted if other rows reference it | When dependent data must not be lost |
CASCADE | Deletes the parent and automatically deletes the child rows | When the child has no meaning without the parent |
SET NULL | Keeps the child row but clears the foreign key | When the relationship is optional |
RESTRICT: don't delete while references exist
With RESTRICT, the database rejects deletion of a parent row as long as at least one child row still references it.
For the relationship orders.user_id → users.id, this is the option I'd usually choose.
If a customer already has orders, deleting their purchase history along with the customer is risky. Financial data is usually retained, so the user is more often kept in the table and marked as inactive, for example with an is_deleted flag or a deleted_at value.
CASCADE: delete everything that depends on it
With CASCADE, the database automatically deletes child rows when the parent is deleted.
This works well when a child row no longer describes anything meaningful without its parent.
For example:
order_items.order_id → orders.id
An order item without its order makes no sense. If you delete a test order, its items can be deleted automatically too.
Use CASCADE carefully: mistakes are especially easy when a cascade runs through several tables in sequence.
For example, with this chain:
order_items.order_id → orders.id
orders.user_id → users.id
one command:
DELETE FROM users
WHERE id = 18;
could delete the user, all of their orders, and every item in those orders. That's unpleasant in a test database; in , it could erase valuable history along with the user.
SET NULL: keep the row, remove the reference
With SET NULL, the child row stays in place, but its foreign key becomes NULL after the parent is deleted.
Suppose a user has an optional reference to a favorite product:
users.favorite_product_id → products.id
If the product disappears from the catalog, deleting the user along with it would make little sense. We can simply clear the reference:
favorite_product_id = NULL
There's one requirement: the column must allow NULL.
If the foreign key is declared NOT NULL, SET NULL won't work.
Can a foreign key be NULL?
Yes. If the column allows NULL, a foreign key can store that value too.
For example:
events.user_id
can be NULL if an event happened without an authenticated user: a guest opened a product page but hadn't signed in yet. Our Kotomarket training database doesn't contain such events: the customer is known for every row in events. Real event logs usually contain many guest events.
Here, NULL means “there is no relationship,” rather than “the relationship is broken.”
The database checks the foreign key when the column contains a specific value. If events.user_id = 18, a row with id = 18 must exist in users. If events.user_id IS NULL, there's nothing to check: the event simply isn't associated with a user.
Interview question
Interview question: What's the difference between a and a ? Can a foreign key be NULL?
Strong answer:
A primary key uniquely identifies a row within its own table. For example, users.id is the unique id of a user. Primary key values don't repeat, and the key itself can't be NULL.
A foreign key stores a reference to a key in another table. For example, orders.user_id contains a value from users.id, so you can use it to determine which user an order belongs to.
The enforces through the foreign key: you can't set orders.user_id = 999999 if no row with users.id = 999999 exists.
A foreign key can be NULL if the column allows NULL. Here, NULL means “there is no relationship.” For example, a guest event may not be associated with any user.
Another common question: what happens when you delete a row that other rows reference?
The answer depends on the ON DELETE setting:
RESTRICT/NO ACTION— the database won't allow the parent row to be deleted;CASCADE— the database deletes the dependent child rows;SET NULL— the database keeps the child rows but clears the foreign key.
orders, and the orders.user_id foreign key uses ON DELETE RESTRICT. What happens when you run DELETE FROM users WHERE id = 18?- All Orders for One CustomerEASY
- Order Count per CustomerEASY
- Number of Orders Containing Each ProductMEDIUM
SELECT o.id AS order_id, o.user_id AS foreign_key, u.full_name AS buyer
FROM orders o
JOIN users u ON u.id = o.user_id
ORDER BY o.id
LIMIT 5;