22. Foreign keys: links that hold
REFERENCES ties a row to a row of another table, and the database makes sure the tie never points at nothing.
What REFERENCES says
In the shop, every order belongs to a customer. The orders table says so in one column:
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customer(id),
ordered TEXT NOT NULL,
status TEXT NOT NULL
);REFERENCES customer(id) makes customer_id a foreign key: its value must be the id of a row that really is in customer. The table that points (orders) is the child; the table pointed at (customer) is the parent. The shop has four such ties:
| Child | Column | Parent |
|---|---|---|
product | category_id | category(id) |
orders | customer_id | customer(id) |
order_item | order_id | orders(id) |
order_item | product_id | product(id) |
The parent's column must be its PRIMARY KEY or a UNIQUE column, so that a value finds exactly one row.
Without this, nothing stops an order for customer 99, who doesn't exist. Reports would then lose orders in a JOIN, or show a nameless customer. A foreign key stops the mistake when it is made, not months later.
What it protects
An order for a customer who isn't there is refused:
INSERT INTO orders (id, customer_id, ordered, status)
VALUES (16, 99, '2026-12-01', 'paid');The other side is protected too. Somchai (customer 1) has orders, so deleting him would leave those orders pointing at nobody:
DELETE FROM customer WHERE id = 1;Changing his id would orphan them just the same:
UPDATE customer SET id = 100 WHERE id = 1;A customer with no orders has no children, so the delete goes through. Lalita (customer 10) hasn't ordered yet:
DELETE FROM customer WHERE id = 10;And NULL in a foreign key is allowed: it means "not linked to anything", not "linked to a row that's missing". A product with no category yet is fine (add NOT NULL to the column when you want a link always there, as orders.customer_id has):
INSERT INTO product (id, name, category_id, price, stock)
VALUES (13, 'Gift Card', NULL, 500, 10);"FOREIGN KEY constraint failed" doesn't say which tie broke. Look at the tables the statement touches and at their REFERENCES: which value points at nothing, or which row still has children?
PRAGMA foreign_keys: on or off
Here is the catch: SQLite doesn't check foreign keys unless you ask it to, on every connection. That was its behaviour before foreign keys existed, and it is kept so old programs don't break. You switch the check on with:
PRAGMA foreign_keys = ON;This guide does that at the start of every chapter. To see the setting, ask without = (1 means on):
PRAGMA foreign_keys;| foreign_keys |
|---|
| 1 |
The setting belongs to the connection, not to the file. Every program that opens the database must run PRAGMA foreign_keys = ON itself, right after opening it, or its changes go unchecked. It can't be changed inside a transaction either: run it before BEGIN.
Let's see what happens with the check off. This order for customer 99 is accepted without a word:
PRAGMA foreign_keys = OFF;
INSERT INTO orders (id, customer_id, ordered, status)
VALUES (16, 99, '2026-12-01', 'paid');Finding broken links with PRAGMA foreign_key_check
Data written while the check was off (or by a program that never turned it on) may hold links to nothing. PRAGMA foreign_key_check looks through every table and lists each row whose link is broken:
PRAGMA foreign_key_check;| table | rowid | parent | fkid |
|---|---|---|---|
| orders | 16 | customer | 0 |
Each row of the result says: the child table, the child row's rowid, the parent table it should point at, and which of the table's foreign keys it is (counting from 0). Here: row 16 of orders points at a customer that isn't there. PRAGMA foreign_key_check(orders) checks one table only.
Fix the row, turn the check back on, and run the check again. No rows means every link holds:
DELETE FROM orders WHERE id = 16;
PRAGMA foreign_keys = ON;
PRAGMA foreign_key_check;| table | rowid | parent | fkid |
|---|
Run PRAGMA foreign_key_check after loading data from outside, after a big repair with the check off, and before you trust an old file. It only reads; it changes nothing.
ON DELETE and ON UPDATE: what happens to the children
So far a parent with children simply can't go. Sometimes you want something else, and the foreign key can say so after ON DELETE (when the parent is deleted) and ON UPDATE (when the parent's key changes):
| Action | What happens to the children |
|---|---|
NO ACTION (the default) | nothing: the statement fails if children are left pointing at nothing |
RESTRICT | the same refusal, checked at once (the difference shows only with deferred checks) |
CASCADE | they follow: deleted with the parent, or given the parent's new key |
SET NULL | their link becomes NULL |
SET DEFAULT | their link becomes the column's DEFAULT |
Let's try them on tables of our own. A shopping cart and its lines: a line means nothing without its cart, so when a cart goes, its lines go too (CASCADE), and if a cart gets a new number, its lines follow:
CREATE TABLE cart (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customer(id)
);
CREATE TABLE cart_line (
cart_id INTEGER NOT NULL REFERENCES cart(id)
ON DELETE CASCADE ON UPDATE CASCADE,
product_id INTEGER NOT NULL REFERENCES product(id),
qty INTEGER NOT NULL
);
INSERT INTO cart VALUES (1, 2), (2, 5);
INSERT INTO cart_line VALUES (1, 1, 2), (1, 4, 1), (2, 8, 3);
SELECT * FROM cart_line;| cart_id | product_id | qty |
|---|---|---|
| 1 | 1 | 2 |
| 1 | 4 | 1 |
| 2 | 8 | 3 |
Give cart 1 the number 10. Its two lines follow it:
UPDATE cart SET id = 10 WHERE id = 1;
SELECT * FROM cart_line;| cart_id | product_id | qty |
|---|---|---|
| 10 | 1 | 2 |
| 10 | 4 | 1 |
| 2 | 8 | 3 |
Now delete cart 10. No error this time: its lines are deleted with it, and only cart 2's line is left:
DELETE FROM cart WHERE id = 10;
SELECT * FROM cart_line;| cart_id | product_id | qty |
|---|---|---|
| 2 | 8 | 3 |
Next, staff and the tasks given to them. When someone leaves, their tasks should stay, just with nobody on them (SET NULL):
CREATE TABLE staff (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE task (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
staff_id INTEGER REFERENCES staff(id) ON DELETE SET NULL
);
INSERT INTO staff VALUES (1, 'Dao'), (2, 'Ton');
INSERT INTO task VALUES (1, 'Count the stock', 1), (2, 'Clean the shelves', 2),
(3, 'Order more pens', 1);
DELETE FROM staff WHERE id = 1;
SELECT * FROM task;| id | title | staff_id |
|---|---|---|
| 1 | Count the stock | NULL |
| 2 | Clean the shelves | 2 |
| 3 | Order more pens | NULL |
Dao's two tasks are still there, waiting for someone (staff_id is NULL). Last, shelves and the products placed on them. A shelf must not go while products are still on it. With RESTRICT the delete is refused, as with the shop's own ties:
CREATE TABLE shelf (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE shelf_product (
shelf_id INTEGER NOT NULL REFERENCES shelf(id) ON DELETE RESTRICT,
product_id INTEGER NOT NULL REFERENCES product(id)
);
INSERT INTO shelf VALUES (1, 'Front'), (2, 'Back');
INSERT INTO shelf_product VALUES (1, 1), (1, 7);DELETE FROM shelf WHERE id = 1;The empty shelf 2 can go:
DELETE FROM shelf WHERE id = 2;CASCADE is powerful: one DELETE can remove rows in many tables, and children of children too. Use it where the children truly mean nothing alone (cart lines, an order's items). For things with a history of their own, such as orders, the default refusal is the safer choice: a customer with orders should not vanish with them.
Choosing well
- Give every column that points at another table a
REFERENCES. It costs a few words and saves the data. - Make the link
NOT NULLwhen it must always be there (an order always has a customer), and leave it nullable when "none yet" is a real answer (a product before it has a category). - Pick the action from the meaning: part of the parent →
CASCADE; can live alone →SET NULL; must not lose its parent → the default (orRESTRICT). - Put an index on the child's column (chapter 25). Each delete or key change of a parent has to look for its children, and without an index it reads the whole child table every time.
- Which customers have no orders, and so could be deleted without an error? (Use
NOT EXISTS.) - Make
album (id, title)andphoto (id, album_id, file)where deleting an album deletes its photos. Add one album with two photos, delete the album, and count the photos left. - Run the check that lists every broken link in the database. What does it give now?
Show the answer
SELECT id, name FROM customer AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id);
CREATE TABLE album (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE photo (
id INTEGER PRIMARY KEY,
album_id INTEGER NOT NULL REFERENCES album(id) ON DELETE CASCADE,
file TEXT NOT NULL
);
INSERT INTO album VALUES (1, 'Opening day');
INSERT INTO photo VALUES (1, 1, 'shop.jpg'), (2, 1, 'cake.jpg');
DELETE FROM album WHERE id = 1;
SELECT COUNT(*) FROM photo;
PRAGMA foreign_key_check;| id | name |
|---|---|
| 9 | Tawan Rungruang |
| COUNT(*) |
|---|
| 0 |
| table | rowid | parent | fkid |
|---|
Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made