A foreign key links a row in one table to a row in another: a book to its author, an invoice to its customer. The database uses that link to protect your data. It refuses a book whose author does not exist, and it decides what happens to the books when an author is deleted. This lesson shows foreign keys in action, including the ON DELETE CASCADE and ON DELETE SET NULL rules.
In this lesson you will learn
- What a foreign key is and what referential integrity means
- How the database rejects invalid inserts and deletes
ON DELETE CASCADE,SET NULLandRESTRICTON UPDATErules- Turning on foreign key checks in SQLite
This lesson builds on SQL constraints and SQL joins.
A Foreign Key Protects Your Data
-- SQLite checks foreign keys only when this is switched on
PRAGMA foreign_keys = ON;
CREATE TABLE authors (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author_id INTEGER NOT NULL REFERENCES authors(id)
);
INSERT INTO authors VALUES (1, 'Humayun Ahmed'), (2, 'Selina Hossain');
INSERT INTO books VALUES (10, 'Nondito Noroke', 1), (11, 'Himu', 1), (12, 'Hangor Nodi Grenade', 2);
-- fails: author 99 does not exist
INSERT INTO books VALUES (13, 'Unknown Book', 99);
-- fails: author 1 still has books
DELETE FROM authors WHERE id = 1;
SELECT b.title, a.name AS author
FROM books b JOIN authors a ON a.id = b.author_id
ORDER BY b.id;
Output
Error: FOREIGN KEY constraint failed
Error: FOREIGN KEY constraint failed
+---------------------+----------------+
| title | author |
+---------------------+----------------+
| Nondito Noroke | Humayun Ahmed |
| Himu | Humayun Ahmed |
| Hangor Nodi Grenade | Selina Hossain |
+---------------------+----------------+
(3 rows)
author_id INTEGER REFERENCES authors(id)declares a foreign key. The table being pointed to (authors) is the parent; the table with the foreign key (books) is the child.- The first error comes from inserting a book with
author_id99. No author has that id, so the row would be an orphan, and the database rejects it. - The second error comes from deleting author 1. Two books still point to that author, and with no delete rule the database refuses rather than leave them pointing at nothing.
- This guarantee, that every foreign key value matches a real parent row, is called referential integrity.
- SQLite only checks foreign keys after
PRAGMA foreign_keys = ON;, which must be run on each connection. MySQL (InnoDB), PostgreSQL and SQL Server always check them.
CASCADE and SET NULL
PRAGMA foreign_keys = ON;
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sales_reps (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE invoices (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id) ON DELETE CASCADE,
rep_id INTEGER REFERENCES sales_reps(id) ON DELETE SET NULL,
total INTEGER
);
INSERT INTO customers VALUES (1, 'Karim'), (2, 'Rina');
INSERT INTO sales_reps VALUES (1, 'Joya'), (2, 'Tuhin');
INSERT INTO invoices VALUES (100, 1, 1, 500), (101, 1, 2, 700), (102, 2, 1, 300);
-- Deleting a customer also deletes their invoices (CASCADE)
DELETE FROM customers WHERE id = 1;
SELECT * FROM invoices;
-- Deleting a sales rep keeps the invoices but clears the link (SET NULL)
DELETE FROM sales_reps WHERE id = 1;
SELECT * FROM invoices;
Output
+-----+-------------+--------+-------+
| id | customer_id | rep_id | total |
+-----+-------------+--------+-------+
| 102 | 2 | 1 | 300 |
+-----+-------------+--------+-------+
(1 row)
+-----+-------------+--------+-------+
| id | customer_id | rep_id | total |
+-----+-------------+--------+-------+
| 102 | 2 | NULL | 300 |
+-----+-------------+--------+-------+
(1 row)
ON DELETE CASCADEoncustomer_idmeans deleting a customer also deletes their invoices. Karim’s invoices 100 and 101 disappeared together with him.ON DELETE SET NULLonrep_idmeans deleting a sales rep keeps the invoice but sets itsrep_idto NULL. Invoice 102 survived, with no rep.- The column must allow NULL for
SET NULLto work. - Choose the rule from the meaning of the data: invoices cannot exist without a customer, but they can outlive the employee who made the sale.
Foreign Key Actions
| Rule | When the parent row is deleted (or its key updated) |
|---|---|
NO ACTION (default) | The change is rejected if child rows still refer to it |
RESTRICT | Rejected immediately, even inside a transaction that would fix it later |
CASCADE | Child rows are deleted (or their keys updated to match) |
SET NULL | The child’s foreign key column becomes NULL |
SET DEFAULT | The child’s foreign key column gets its default value |
The same rules can be given for updates with ON UPDATE, for example ON UPDATE CASCADE to follow a parent whose key changes. A full declaration also works as a table constraint: FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE.
Common Mistakes
- Forgetting
PRAGMA foreign_keys = ONin SQLite, so no checks happen at all. - Using CASCADE everywhere. One delete can silently remove thousands of rows in several tables.
- Not indexing the foreign key column. Joins and parent deletes then scan the whole child table. PostgreSQL and SQLite do not create this index for you; MySQL does.
- Using SET NULL on a NOT NULL column, which makes the delete fail.
Practice Exercises
Exercise 1. Create a comments table whose comments are removed automatically when their post is deleted.
Show answer
CREATE TABLE comments (
id INTEGER PRIMARY KEY,
post_id INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
body TEXT NOT NULL
);
Exercise 2. In the first example, how could you delete author 1 without an error, while keeping everything consistent?
Show answer
Delete the child rows first, then the parent: DELETE FROM books WHERE author_id = 1; followed by DELETE FROM authors WHERE id = 1;. Run both inside a transaction so they succeed or fail together. Alternatively, define the key with ON DELETE CASCADE.
Frequently Asked Questions
Can a foreign key point to a column that is not the primary key?
Yes, as long as that column has a UNIQUE constraint, so each value identifies exactly one parent row.
Can a table have a foreign key to itself?
Yes. An employees table can have manager_id REFERENCES employees(id), which models a hierarchy you can query with a self join or a recursive CTE.
Summary
- A foreign key makes each child row point to a real parent row.
- Invalid inserts and unsafe deletes are rejected.
CASCADEdeletes children,SET NULLclears the link.- Index foreign key columns, and switch checks on in SQLite.
Next: Table Relationships: One-to-One, One-to-Many and Many-to-Many.
