Siti wants to close her Sunset Coffee account, and she has 2 orders. When her row is deleted from customers, what should happen to those orders: thrown away too, marked as "guest", or is the delete refused? The database can carry out that choice by itself, as long as you write the rule into the foreign key.
Two terms first, through Sunset Coffee's membership card. The card number is unique and never changes, even when the owner changes their name. The card number is the primary key of the customers table: a column (or a combination of columns) whose value is unique in every row, so one row can be pointed at for certain. Every receipt records only the member number from that card, not the customer's full details. A receipt is a row in orders, and the member number on it is a foreign key: a column holding another table's primary key. A foreign key is a pointer from a child row (here, an order) to its parent row (the customer who owns the order).
Primary key: every row's ID card
A primary key has two properties: it is unique and it can't be empty (NULL). SQLite has an exception: a primary key that isn't an INTEGER PRIMARY KEY can accept NULL unless you write NOT NULL. A table has only one primary key. Try adding a customer with the id Siti already uses (id 2). The -- line below it is the error SQLite replies with:
INSERT INTO customers (id, name) VALUES (2, 'Rina');
-- UNIQUE constraint failed: customers.id
There are four ways to choose a primary key:
| Kind | Example | When to use it |
|---|---|---|
| Auto-increment | id INTEGER PRIMARY KEY (SQLite), AUTO_INCREMENT (MySQL), GENERATED ALWAYS AS IDENTITY (PostgreSQL) |
the most common choice, the database fills in 1, 2, 3 |
| UUID | '3f2b9c1e-...', made by the app or by gen_random_uuid() in PostgreSQL |
ids created on many servers, or ids that mustn't be guessable from a URL |
| Natural key | country code 'GB', 'JP' |
a real-world value guaranteed to be unique and never to change |
| Composite key | PRIMARY KEY (order_id, product_id) in order_items |
linking tables, as in the Second Normal Form (2NF) lesson |
A UUID is a long code (36 characters) that is practically never the same twice, even when it is made on many servers. Composite key is another name for a combined primary key.
Pick a value that never changes. Email and phone number look unique, but their owners can change them. When that happens, every foreign key pointing at them would have to change too. That's why most tables use an auto-increment id.
Foreign key: a pointer to another primary key
You already wrote foreign keys in the SQL lesson on table relationships. Here is Sunset Coffee's orders table, now with a rule for when its customer is deleted:
PRAGMA foreign_keys = ON;
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id) ON DELETE SET NULL,
total INTEGER NOT NULL
);
INSERT INTO customers VALUES (1, 'Budi'), (2, 'Siti'), (3, 'Andi');
INSERT INTO orders VALUES (1, 1, 1400), (2, 1, 550), (3, 2, 825), (4, 2, 450), (5, 3, 375);
INSERT INTO orders (customer_id, total) VALUES (9, 500);
-- FOREIGN KEY constraint failed
REFERENCES customers(id)makescustomer_ida foreign key to the primary key ofcustomers. Customer 9 doesn't exist, so the order is refused.ON DELETE SET NULLdecides what happens to the orders when their customer is deleted. The next section covers the choices.customer_iddeliberately has noNOT NULL, soSET NULLcan empty it.PRAGMA foreign_keys = ON;is SQLite only (the Lab, the Playground). Without it, SQLite doesn't check foreign keys at all, and you have to run it again on every connection to the database (each time a program opens the database). MySQL (with InnoDB, its default storage engine) and PostgreSQL check foreign keys without being switched on.
ON DELETE: what happens to the child rows
customers is the parent table. orders is the child table, because each of its rows points at one parent row. These are the results of DELETE FROM customers WHERE id = 2; (Siti, owner of orders 3 and 4) in real SQLite, for each ON DELETE choice:
| ON DELETE | Result of the DELETE | Orders 3 and 4 |
|---|---|---|
CASCADE |
succeeds | deleted too |
SET NULL |
succeeds | kept, customer_id becomes NULL |
RESTRICT |
refused: FOREIGN KEY constraint failed |
kept, and so is Siti |
NO ACTION (the default when nothing is written) |
refused: FOREIGN KEY constraint failed |
kept, and so is Siti |
With SET NULL, Siti's orders stay, without an owner.
- CASCADE fits when a child means nothing without its parent:
order_itemsare deleted with theirorders, or every post is deleted when a user deletes their account. - SET NULL fits when the child must stay: the author is deleted, the post is still shown without an author.
- RESTRICT fits when deleting must be refused while children exist: a department can't be deleted while it still has employees.
- NO ACTION is the SQL default. It differs from
RESTRICTonly in when it checks:RESTRICTright away,NO ACTIONat the end of the statement (one SQL command). PostgreSQL can even delay theNO ACTIONcheck to the end of the transaction. In MySQL with InnoDB, the two are exactly the same. There's alsoSET DEFAULT(it fills in the column's default value), rarely used.
For a shop's orders, CASCADE from customers is almost always wrong: deleting a customer would also delete sales records and the accounts. Pick RESTRICT or SET NULL.
In Laravel: foreignId()->constrained()
A Laravel migration (a PHP file that creates and changes tables) writes the same foreign keys more briefly:
$table->foreignId('customer_id')->constrained(); // REFERENCES customers(id)
$table->foreignId('order_id')->constrained()->cascadeOnDelete(); // ON DELETE CASCADE
$table->foreignId('author_id')->nullable()->constrained('users')->nullOnDelete(); // ON DELETE SET NULL
$table->foreignId('department_id')->constrained()->restrictOnDelete(); // ON DELETE RESTRICT
foreignId('customer_id')creates a number column that matches an auto-incrementid.constrained()creates the foreign key and guesses the table from the column name:customer_idpoints to thecustomerstable, columnid. When the name doesn't match, name the table:constrained('users').cascadeOnDelete()is the same asonDelete('cascade'), which you'll see in older tutorials.nullable()comes beforeconstrained(), and is required fornullOnDelete().constrained()creates no index (the next lesson, Indexes & Performance, covers indexes). MySQL creates an index on a foreign key column by itself, but PostgreSQL and SQLite do not. Without an index, a query such as "all of Siti's orders" (WHERE customer_id = ?) and theON DELETEcheck must read the wholeorderstable. In PostgreSQL and SQLite, add the index yourself:$table->foreignId('customer_id')->index()->constrained();.
⚠️ Delete rules that stay silent, fail, or go too far
- Forgetting
PRAGMA foreign_keys = ONin SQLite. Without it, evenON DELETE CASCADEdoesn't run. Siti is deleted, and her orders are left pointing at a customer who doesn't exist. SET NULLon aNOT NULLcolumn. Deleting Siti fails withNOT NULL constraint failed: orders.customer_id. The column has to allowNULL.CASCADEin the wrong place. OneDELETEof a customer can remove hundreds of orders without a warning.- A primary key made of data that can change. If an email or a phone number is the primary key, every foreign key pointing at it has to change whenever the value changes.
- The text in the exercise. Your function returns exactly
"CASCADE","SET NULL","RESTRICT"or"NO ACTION", all uppercase and with the space inSET NULL.
TL;DR: Primary key = a unique column that can't be NULL (empty), so one row can be pointed at for certain. Its kinds: auto-increment (a number the database fills in), UUID (a long code that is practically never the same twice), natural key (a real-world value) or composite key (a combination of columns). Pick a value that never changes. Foreign key = a column that points at another table's primary key. The database refuses a pointer to a row that doesn't exist (the error FOREIGN KEY constraint failed; in SQLite only after PRAGMA foreign_keys = ON). ON DELETE decides what happens to the child rows (orders) when their parent row (the customer) is deleted: CASCADE deletes them too, SET NULL empties the pointer, RESTRICT refuses, NO ACTION (the default) refuses as well. In a Laravel migration (a PHP file that creates tables): $table->foreignId('customer_id')->constrained(), plus cascadeOnDelete(), nullOnDelete() or restrictOnDelete().
⚡ Primary key: every row's ID card
Write:
INSERT INTO customers (id, name) VALUES (2, 'Rina');
-- UNIQUE constraint failed: customers.id
Meaning: A primary key is the identity number of each row: unique and never NULL (empty), so one row can be pointed at for certain. Siti already uses id 2 in customers, so SQLite refuses Rina's row with the error on the -- line. Pick a value that never changes, like an auto-increment id (a number the database fills in).
⚡ Foreign key: a pointer to another table
Write:
INSERT INTO orders (customer_id, total) VALUES (9, 500);
-- FOREIGN KEY constraint failed
Meaning: A foreign key links tables by pointing at another table's primary key. Here orders.customer_id points at customers.id. Customer 9 isn't in customers, so the order is refused. In SQLite, this check only runs after PRAGMA foreign_keys = ON;.
⚡ ON DELETE: what happens to the children
Guess first: ON DELETE on a foreign key decides what happens to the orders when their customer is deleted. Siti is deleted from customers. With ON DELETE SET NULL, what happens to her orders?
They stay, but their customer_id becomes NULL: orders without an owner.
Meaning: When a parent row (the customer) is deleted, CASCADE deletes the child rows (her orders) too, SET NULL empties their pointer, and RESTRICT and NO ACTION (the default when nothing is written) refuse the delete.
In the exercise, your function returns exactly "CASCADE", "SET NULL", "RESTRICT" or "NO ACTION", all uppercase.