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:

ChildColumnParent
productcategory_idcategory(id)
orderscustomer_idcustomer(id)
order_itemorder_idorders(id)
order_itemproduct_idproduct(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');
Error: FOREIGN KEY constraint failed

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;
Error: FOREIGN KEY constraint failed

Changing his id would orphan them just the same:

UPDATE customer SET id = 100 WHERE id = 1;
Error: FOREIGN KEY constraint failed

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;
✓ 1 row changed

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);
✓ 1 row changed

"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
1 row

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');
✓ 1 row changed

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;
tablerowidparentfkid
orders16customer0
1 row

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;
tablerowidparentfkid
no rows

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):

ActionWhat happens to the children
NO ACTION (the default)nothing: the statement fails if children are left pointing at nothing
RESTRICTthe same refusal, checked at once (the difference shows only with deferred checks)
CASCADEthey follow: deleted with the parent, or given the parent's new key
SET NULLtheir link becomes NULL
SET DEFAULTtheir 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_idproduct_idqty
112
141
283
3 rows

Give cart 1 the number 10. Its two lines follow it:

UPDATE cart SET id = 10 WHERE id = 1;
SELECT * FROM cart_line;
cart_idproduct_idqty
1012
1041
283
3 rows

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_idproduct_idqty
283
1 row

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;
idtitlestaff_id
1Count the stockNULL
2Clean the shelves2
3Order more pensNULL
3 rows

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);
✓ 2 rows changed
DELETE FROM shelf WHERE id = 1;
Error: FOREIGN KEY constraint failed

The empty shelf 2 can go:

DELETE FROM shelf WHERE id = 2;
✓ 1 row changed

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

  1. Which customers have no orders, and so could be deleted without an error? (Use NOT EXISTS.)
  2. Make album (id, title) and photo (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.
  3. 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;
idname
9Tawan Rungruang
1 row
COUNT(*)
0
1 row
tablerowidparentfkid
no rows

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