Sub topic 7
Foreign keys: linking tables
This chapter assumes you know what a table, a row, and a primary key are, and that you can read basic CREATE TABLE and SELECT statements. It covers what a foreign key is, how the database enforces it, what happens when you delete or update a referenced row, and the errors people hit most often.
What a foreign key is
A foreign key is a column (or a group of columns) in one table whose values must match a key in another table. The table that holds the foreign key is the child table. The table it points to is the parent table. The target is usually the parent's primary key, though it can be any column or column group with a UNIQUE constraint.
In the schema from earlier chapters, orders.customer_id is a foreign key that points to customers.customer_id:
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
order_date DATE NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0)
);The clause REFERENCES customers (customer_id) creates the link. An order stores only the customer's ID, not the customer's name or email. The name and email live in one place, and every order points to them.
The rule the database enforces
A foreign key states one rule, called referential integrity: every value in the foreign key column must either exist in the referenced column of the parent table or be NULL.
The database checks this rule on every change that could break it:
- Inserting or updating a child row with a value that has no parent is rejected.
- Deleting or updating a parent row that still has child rows is rejected, or triggers a configured action (see below).
INSERT INTO customers (customer_id, name, email)
VALUES (1, 'Ada Lovelace', '[email protected]');
-- Works: customer 1 exists.
INSERT INTO orders (order_id, customer_id, order_date, total_amount)
VALUES (100, 1, '2026-01-15', 59.90);
-- Fails: no customer 99.
INSERT INTO orders (order_id, customer_id, order_date, total_amount)
VALUES (101, 99, '2026-01-16', 20.00);The last statement raises an error such as violates foreign key constraint (PostgreSQL) or FOREIGN KEY constraint failed (SQLite). The exact wording differs between systems, but the statement is rejected and no row is written.
Without the constraint, the bad insert would succeed. You would then have an "orphan" row: an order that belongs to a customer who does not exist. Every query that joins orders to customers would silently drop that order, and the problem would be hard to trace.
Declaring foreign keys
There are two equivalent syntaxes. The inline form attaches REFERENCES to the column, as shown above. The table-level form lists the constraint separately and lets you give it a name:
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
order_date DATE NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0),
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);Naming the constraint matters in practice. The name appears in error messages, and you need it to drop or change the constraint later. You can also add a foreign key to an existing table:
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id);ALTER TABLE ... ADD CONSTRAINT fails if existing rows already violate the rule, so you must clean up orphans first. SQLite is a special case. It does not support adding a foreign key to an existing table with ALTER TABLE, so you declare it when you create the table or rebuild the table.
What happens when the parent changes
By default, the database refuses to delete a parent row that children still reference. You can choose a different behavior with referential actions on ON DELETE and ON UPDATE.
| Action | Effect when the parent row is deleted or its key is updated |
|---|---|
| `NO ACTION` | Reject the change. This is the default. The check happens at the end of the statement. |
| `RESTRICT` | Reject the change immediately. It differs from `NO ACTION` only when constraints are deferred. |
| `CASCADE` | Apply the same change to the child rows: delete them, or update their key value. |
| `SET NULL` | Set the child's foreign key column to `NULL`. The column must allow `NULL`. |
| `SET DEFAULT` | Set the child's foreign key column to its default value. The default must exist in the parent. |
Here is a schema where deleting a customer also deletes their orders, and where deleting a product's category only clears the link:
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
order_date DATE NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0),
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
ON DELETE CASCADE
);With ON DELETE CASCADE, running DELETE FROM customers WHERE customer_id = 1; removes the customer and all of their orders in one statement.
Use SET NULL when the child can exist without the parent. For example, a tickets.assigned_to column can become NULL when an employee row is deleted. That column must be declared without NOT NULL.
Nullable foreign keys and optional relationships
A foreign key column is NULL-able unless you add NOT NULL. A NULL value means "no parent", and the database does not check it against the parent table. This gives you a way to model optional relationships.
customer_id INTEGER NOT NULL REFERENCES ...means every order must have a customer. The relationship is mandatory.manager_id INTEGER REFERENCES employees (employee_id)means an employee may have no manager. The relationship is optional.
When you design a table, decide for each foreign key whether the child can exist without a parent. Forgetting NOT NULL is a common mistake: the constraint then guards against wrong IDs but still allows a missing one.
Foreign keys and relationships
A foreign key on the "many" side models a one-to-many relationship. One customer has many orders, and each order has one customer. The foreign key sits in orders, the many side.
A many-to-many relationship needs a junction table whose columns are two foreign keys:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
product_id INTEGER NOT NULL REFERENCES products (product_id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id)
);Each row in order_items links one order to one product. The composite primary key (order_id, product_id) prevents the same product from appearing twice in the same order. A later chapter covers these relationships in detail.
A foreign key can also point to the same table. This is a self-reference, used for hierarchies such as employees and managers:
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
manager_id INTEGER REFERENCES employees (employee_id)
);The top of the hierarchy has manager_id set to NULL.
Using foreign keys in queries
The foreign key does not change how queries work, since you still write the join yourself. What it guarantees is that the join finds a match for every non-null value:
SELECT c.name, o.order_id, o.order_date, o.total_amount
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY o.order_date;The ON clause compares the foreign key with the primary key it references. Joins are covered in their own chapter.
Indexes on foreign keys
Most databases index the primary key automatically, but PostgreSQL and SQLite do not create an index on the referencing (child) column. MySQL's InnoDB does create one if none exists. Without an index, two operations scan the whole child table:
- Finding all orders for one customer.
- Checking whether a parent row still has children when you delete or update it.
For this reason, index foreign key columns that you query or whose parents you delete:
CREATE INDEX idx_orders_customer_id ON orders (customer_id);The cost is extra storage and slightly slower writes, which a later chapter explains.
Common errors and gotchas
- Referenced column is not unique. The target of a foreign key must be a primary key or have a
UNIQUEconstraint. Otherwise the database could not tell which parent row you mean, and it rejects the declaration. - Mismatched types. The child column and the parent column should have the same type. Pointing a
VARCHARcolumn at anINTEGERkey fails or forces implicit conversions, depending on the system. - Creating tables in the wrong order. The parent table must exist before a child can reference it. Create
customersbeforeorders. For circular references, create the tables first and add one constraint afterwards withALTER TABLE. - Deleting in the wrong order. With the default action, delete child rows before the parent row, or the delete fails.
- Orphans from existing data. Adding a constraint to a table that already holds bad data fails until you fix or remove the orphan rows. You can find them with a left join:
SELECT o.order_id, o.customer_id
FROM orders AS o
LEFT JOIN customers AS c ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL;- Assuming a foreign key validates meaning. The constraint checks that the parent exists, not that it is the right parent. An order pointing to the wrong valid customer passes.
- Composite keys. If the parent has a composite primary key, the foreign key must list all of its columns in the same order. A composite foreign key with a
NULLin one column is treated differently across systems, so avoid nullable parts in composite foreign keys.
Summary of the design decision
For each relationship, answer these questions, in this order:
- Which table is the parent and which is the child? The foreign key goes in the child.
- Is the parent mandatory? If yes, add
NOT NULL. - What should happen when the parent is deleted? Choose among reject, cascade, and set null.
- Will you query children by parent? If yes, add an index on the foreign key column.
Exercise
A table tickets has a column assigned_to that references employees (employee_id). Tickets can be unassigned, and when an employee is deleted, their tickets must stay in the system as unassigned. Write the column definition and the referential action that does this. Then explain what happens if you leave out the ON DELETE clause.
Show answer
Use assigned_to INTEGER REFERENCES employees (employee_id) ON DELETE SET NULL. The column has no NOT NULL, so it can hold NULL for unassigned tickets, and SET NULL writes NULL into it when the employee row is deleted. Without the ON DELETE clause, the default NO ACTION applies, so deleting an employee who still has assigned tickets fails with a foreign key violation.
Exercise
You run INSERT INTO orders (order_id, customer_id, order_date, total_amount) VALUES (102, 42, '2026-02-01', 10.00); in SQLite and it succeeds, although no customer 42 exists. Give the most likely cause and the fix.
Show answer
SQLite does not enforce foreign keys unless they are switched on for the connection. Run PRAGMA foreign_keys = ON; right after opening each connection. Then the insert fails with FOREIGN KEY constraint failed. Existing orphan rows can be found with a left join from orders to customers where the customer's key is NULL.