Database Foreign Keys
What you will learn
- What a foreign key is and what it points to
- Why we link tables instead of copying data
- How to declare a foreign key with
REFERENCES - Why SQLite needs
PRAGMA foreign_keys = ON - How to read a link back with a
JOIN
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It creates a few new tables in your browser's copy of the data; Reset data starts again.
1. Pointing instead of copying
Imagine an orders table where every row repeats the customer's name and phone number. If a customer changes their phone number, you must fix every one of their orders, and missing one leaves two different numbers for the same person.
The better design keeps each fact once. The customer lives in a customers table. Each order stores only the customer's primary key (lesson 2.4), a small id that points to the right row.
A column that holds the primary key of a row in another table is a foreign key. The table it points to is the parent (here customers); the table that holds the foreign key is the child (here orders).
customers orders
+----+------+ +----+-------------+---------+
| id | name | | id | customer_id | item |
+----+------+ +----+-------------+---------+
| 1 | Rina | <---------- | 1 | 1 | Shirt |
| 2 | Sam | <-----+---- | 2 | 1 | Scarf |
+----+------+ +---- | 3 | 2 | Cap |
+----+-------------+---------+
The Shop database is built this way. In orders, the column customer_id is a foreign key to customers.customer_id. Ask the database what links a table points to:
PRAGMA foreign_key_list(orders);
id seq table from to on_update on_delete match
-- --- --------- ----------- ----------- --------- --------- -----
0 0 employees employee_id employee_id NO ACTION NO ACTION NONE
1 0 customers customer_id customer_id NO ACTION NO ACTION NONE
(2 rows)
Each row is one link: the column of the child table (from) and the parent table and column it points to (table, to).
The Bank database is built this way. In accounts, the column customer_id is a foreign key to customers.customer_id, and branch_id points to branches. Ask the database what links a table points to:
PRAGMA foreign_key_list(accounts);
id seq table from to on_update on_delete match
-- --- --------- ----------- ----------- --------- --------- -----
0 0 branches branch_id branch_id NO ACTION NO ACTION NONE
1 0 customers customer_id customer_id NO ACTION NO ACTION NONE
(2 rows)
Each row is one link: the column of the child table (from) and the parent table and column it points to (table, to).
The School database is built this way. In sections, the column course_id is a foreign key to courses.course_id, and teacher_id points to teachers. Ask the database what links a table points to:
PRAGMA foreign_key_list(sections);
id seq table from to on_update on_delete match
-- --- -------- ---------- ---------- --------- --------- -----
0 0 teachers teacher_id teacher_id NO ACTION NO ACTION NONE
1 0 courses course_id course_id NO ACTION NO ACTION NONE
(2 rows)
Each row is one link: the column of the child table (from) and the parent table and column it points to (table, to).
Quick check: which table is the child, and which column is the foreign key?
In the diagram above, orders is the child, and customer_id is the foreign key. It holds values from customers.id.
2. Declaring a foreign key
You declare the link with REFERENCES (lessons on tables and keys are in chapter 2). Here we create a new child table:
Customers can save products they like in a wish list:
CREATE TABLE wishlists (
wishlist_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
product_id INTEGER NOT NULL REFERENCES products (product_id),
added_on TEXT NOT NULL
);
INSERT INTO wishlists (customer_id, product_id, added_on)
VALUES (1, 5, '2026-09-01'), (1, 9, '2026-09-02'), (2, 5, '2026-09-03');
SELECT * FROM wishlists ORDER BY wishlist_id;
wishlist_id customer_id product_id added_on
----------- ----------- ---------- ----------
1 1 5 2026-09-01
2 1 9 2026-09-02
3 2 5 2026-09-03
(3 rows)
Customers can save the people they pay often (payees):
CREATE TABLE payees (
payee_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
name TEXT NOT NULL,
added_on TEXT NOT NULL
);
INSERT INTO payees (customer_id, name, added_on)
VALUES (1, 'City Water', '2026-09-01'), (1, 'Landlord', '2026-09-02'), (2, 'City Water', '2026-09-03');
SELECT * FROM payees ORDER BY payee_id;
payee_id customer_id name added_on
-------- ----------- ---------- ----------
1 1 City Water 2026-09-01
2 1 Landlord 2026-09-02
3 2 City Water 2026-09-03
(3 rows)
Teachers can write short notes about a student:
CREATE TABLE student_notes (
note_id INTEGER PRIMARY KEY,
student_id INTEGER NOT NULL REFERENCES students (student_id),
note TEXT NOT NULL,
written_on TEXT NOT NULL
);
INSERT INTO student_notes (student_id, note, written_on)
VALUES (1, 'Great project', '2026-09-01'), (1, 'Needs a quieter seat', '2026-09-02'), (2, 'Helps others', '2026-09-03');
SELECT * FROM student_notes ORDER BY note_id;
note_id student_id note written_on
------- ---------- -------------------- ----------
1 1 Great project 2026-09-01
2 1 Needs a quieter seat 2026-09-02
3 2 Helps others 2026-09-03
(3 rows)
The line ... INTEGER NOT NULL REFERENCES parent (column) means: this column must hold a value that exists in the parent column, and it must not be empty.
3. SQLite checks foreign keys only if you ask
Here is a surprise. In SQLite, foreign key checking is off unless you switch it on for each connection. The sample databases switch it on for you, which is why bad rows were refused so far. Check it, then switch it off to see what happens without it:
PRAGMA foreign_keys;
foreign_keys
------------
1
(1 row)
1 means on. Now switch it off and add a wish for customer 99999, who does not exist:
PRAGMA foreign_keys = OFF;
INSERT INTO wishlists (customer_id, product_id, added_on) VALUES (99999, 5, '2026-10-01');
SELECT wishlist_id, customer_id, product_id FROM wishlists WHERE customer_id = 99999;
wishlist_id customer_id product_id
----------- ----------- ----------
4 99999 5
(1 row)
PRAGMA foreign_keys;
foreign_keys
------------
1
(1 row)
1 means on. Now switch it off and add a payee for customer 99999, who does not exist:
PRAGMA foreign_keys = OFF;
INSERT INTO payees (customer_id, name, added_on) VALUES (99999, 'Ghost Ltd', '2026-10-01');
SELECT payee_id, customer_id, name FROM payees WHERE customer_id = 99999;
payee_id customer_id name
-------- ----------- ---------
4 99999 Ghost Ltd
(1 row)
PRAGMA foreign_keys;
foreign_keys
------------
1
(1 row)
1 means on. Now switch it off and add a note for student 99999, who does not exist:
PRAGMA foreign_keys = OFF;
INSERT INTO student_notes (student_id, note, written_on) VALUES (99999, 'Ghost note', '2026-10-01');
SELECT note_id, student_id, note FROM student_notes WHERE student_id = 99999;
note_id student_id note
------- ---------- ----------
4 99999 Ghost note
(1 row)
The database happily stored a row for a parent that does not exist: an orphan row. Now clean up and switch checking on again:
DELETE FROM wishlists WHERE customer_id = 99999;
PRAGMA foreign_keys = ON;
PRAGMA foreign_keys;
foreign_keys
------------
1
(1 row)
Now the database protects the link:
INSERT INTO wishlists (customer_id, product_id, added_on) VALUES (99999, 5, '2026-10-01');
IntegrityError: FOREIGN KEY constraint failed
DELETE FROM payees WHERE customer_id = 99999;
PRAGMA foreign_keys = ON;
PRAGMA foreign_keys;
foreign_keys
------------
1
(1 row)
Now the database protects the link:
INSERT INTO payees (customer_id, name, added_on) VALUES (99999, 'Ghost Ltd', '2026-10-01');
IntegrityError: FOREIGN KEY constraint failed
DELETE FROM student_notes WHERE student_id = 99999;
PRAGMA foreign_keys = ON;
PRAGMA foreign_keys;
foreign_keys
------------
1
(1 row)
Now the database protects the link:
INSERT INTO student_notes (student_id, note, written_on) VALUES (99999, 'Ghost note', '2026-10-01');
IntegrityError: FOREIGN KEY constraint failed
Two details matter:
- The setting belongs to the connection, so a program must run
PRAGMA foreign_keys = ONevery time it connects. - SQLite ignores the setting inside an open transaction. Try to switch it off after
BEGINand look at the answer:
BEGIN;
PRAGMA foreign_keys = OFF;
PRAGMA foreign_keys;
ROLLBACK;
foreign_keys
------------
1
(1 row)
BEGIN;
PRAGMA foreign_keys = OFF;
PRAGMA foreign_keys;
ROLLBACK;
foreign_keys
------------
1
(1 row)
BEGIN;
PRAGMA foreign_keys = OFF;
PRAGMA foreign_keys;
ROLLBACK;
foreign_keys
------------
1
(1 row)
It still says 1: the request was ignored. Programs that use a library which opens a transaction quietly before the first INSERT (Python's sqlite3 module does) must therefore switch the setting on right after connecting, before any other statement.
This is a SQLite habit: its documentation says foreign keys are off by default for backward compatibility. Other database systems have their own defaults, so check the documentation of the one you use.
4. Two more facts about the link
The parent column must be unique. A foreign key points at one specific row, so the column it points to must be a primary key or a UNIQUE column. Point it at an ordinary column and SQLite complains the first time you use it:
Supplier emails are not unique in the suppliers table:
CREATE TABLE supplier_notes (
note_id INTEGER PRIMARY KEY,
supplier_email TEXT REFERENCES suppliers (email),
note TEXT
);
(done)
The table is created, but using it fails:
INSERT INTO supplier_notes (supplier_email, note) VALUES ('northwind.trading@example.com', 'Late delivery');
OperationalError: foreign key mismatch - "supplier_notes" referencing "suppliers"
Customer names are not unique in the customers table (two customers can share a name):
CREATE TABLE complaints_by_name (
complaint_id INTEGER PRIMARY KEY,
customer_name TEXT REFERENCES customers (full_name),
text TEXT
);
(done)
The table is created, but using it fails:
INSERT INTO complaints_by_name (customer_name, text) VALUES ('Chen Park', 'Card not working');
OperationalError: foreign key mismatch - "complaints_by_name" referencing "customers"
Guardian names are not unique in the students table:
CREATE TABLE guardian_notes (
note_id INTEGER PRIMARY KEY,
guardian TEXT REFERENCES students (guardian_name),
note TEXT
);
(done)
The table is created, but using it fails:
INSERT INTO guardian_notes (guardian, note) VALUES ('Hugo Alvarez', 'Called the office');
OperationalError: foreign key mismatch - "guardian_notes" referencing "students"
Making the parent column UNIQUE (lesson 2.6) would fix it. (Even better: point at the primary key, as we did before.)
A foreign key may be empty, unless you forbid it. NULL means "no parent". The NOT NULL we wrote on the foreign keys above made the link required. Without it, the link is optional:
In the real orders table, the column employee_id is optional (online orders have no sales person), while customer_id is required:
SELECT order_id, customer_id, employee_id FROM orders WHERE employee_id IS NULL ORDER BY order_id LIMIT 3;
order_id customer_id employee_id
-------- ----------- -----------
21 146 NULL
23 69 NULL
32 305 NULL
(3 rows)
INSERT INTO orders (customer_id, order_date, status, ship_city) VALUES (NULL, '2026-10-01', 'paid', 'Dhaka');
IntegrityError: NOT NULL constraint failed: orders.customer_id
A card request can come before an account is chosen, so its account link is optional:
CREATE TABLE card_requests (
request_id INTEGER PRIMARY KEY,
account_id INTEGER REFERENCES accounts (account_id),
requested_on TEXT NOT NULL
);
INSERT INTO card_requests (account_id, requested_on) VALUES (NULL, '2026-10-01');
SELECT * FROM card_requests;
request_id account_id requested_on
---------- ---------- ------------
1 NULL 2026-10-01
(1 row)
A new club may not have a teacher yet, so its teacher link is optional:
CREATE TABLE clubs (
club_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
teacher_id INTEGER REFERENCES teachers (teacher_id)
);
INSERT INTO clubs (name, teacher_id) VALUES ('Chess', NULL);
SELECT * FROM clubs;
club_id name teacher_id
------- ----- ----------
1 Chess NULL
(1 row)
A row with no parent is accepted where the link is optional, and refused where it is required. A NULL is not checked against the parent table at all, because it points at nothing. Lesson 3.7 returns to required and optional links.
5. Reading the link back with JOIN
The data is now split over two tables. A JOIN puts it together again (lesson 4.5 covers joins fully):
SELECT w.wishlist_id, c.first_name, c.last_name, p.name AS product
FROM wishlists w
JOIN customers c ON c.customer_id = w.customer_id
JOIN products p ON p.product_id = w.product_id
ORDER BY w.wishlist_id;
wishlist_id first_name last_name product
----------- ---------- --------- --------------
1 Vik Ahmed Chopping board
2 Vik Ahmed Watering can
3 Wanda Ahmed Chopping board
(3 rows)
SELECT p.payee_id, c.full_name, p.name AS payee
FROM payees p
JOIN customers c ON c.customer_id = p.customer_id
ORDER BY p.payee_id;
payee_id full_name payee
-------- ---------- ----------
1 Chen Park City Water
2 Chen Park Landlord
3 Rafi Uddin City Water
(3 rows)
SELECT n.note_id, s.first_name, s.last_name, n.note
FROM student_notes n
JOIN students s ON s.student_id = n.student_id
ORDER BY n.note_id;
note_id first_name last_name note
------- ---------- --------- --------------------
1 Vera Khan Great project
2 Vera Khan Needs a quieter seat
3 Elena Haque Helps others
(3 rows)
ON c.customer_id = w.customer_id (or the matching condition in your database) is the rule that matches each row to its parent. Change a customer's name once in the parent table and every row that points to it shows the new name.
Worked example: spot the foreign key
A school database has students(id, name, class_id) and classes(id, title, room).
| Question | Answer |
|---|---|
| Which column is a foreign key? | students.class_id |
| What does it point to? | classes.id |
| Parent and child? | classes is the parent, students is the child |
What does a student row with class_id = 7 mean? |
that student belongs to the class whose id is 7 |
Names are made up.
Common mistakes
- Forgetting
PRAGMA foreign_keys = ONin SQLite, so bad links are accepted silently. - Turning it on too late, inside a transaction, where it has no effect.
- Pointing at a column that is not unique. A foreign key must point to a primary key or another unique column; otherwise SQLite reports
foreign key mismatch. - Storing the name instead of the id, which brings back the repeated-data problem.
Key takeaways
- A foreign key is a column in the child table that holds the primary key of a row in the parent table.
- Linking keeps each fact in one place, so one change fixes it everywhere.
- Declare it with
REFERENCES parent(column); the parent column must be unique. NOT NULLmakes the link required; without it,NULLmeans "no parent".- In SQLite, switch checking on with
PRAGMA foreign_keys = ONright after connecting. - Use a
JOINto read the linked data together.
Practice
1. In orders(id, customer_id, item), which column is the foreign key?
Show answer
customer_id.
2. Why store customer_id rather than the customer's name in each order?
Show answer
The name is kept once in customers, so a change is made in one place and there is no risk of two different spellings.
3. A table pets(id, owner_id INTEGER REFERENCES owners(id)) has no NOT NULL on owner_id. Is INSERT INTO pets VALUES (1, NULL) accepted or refused? Why?
Show answer
Accepted. NULL means "no owner", and a foreign key only checks values that point at something. Adding NOT NULL would make the owner required.
4. What is an orphan row?
Show answer
A child row whose foreign key points to a parent row that does not exist, such as an order for customer 99 when there is no customer 99.
5. A program connects, inserts a row, and only then runs PRAGMA foreign_keys = ON. Foreign keys are still not checked. Why, and what is the fix?
Show answer
The INSERT opened a transaction, and SQLite ignores the pragma inside a transaction. Run the pragma right after connecting, before any other statement (or commit first).
6. Write the column definition for a foreign key author_id in books that points to authors(id) and cannot be empty.
Show answer
author_id INTEGER NOT NULL REFERENCES authors(id)