You shop at a minimarket with a member card, then look at the receipt. All it says is "member number 1". No name, no address, no phone number. When the cashier needs your name, they find number 1 in the member list. So the member details are stored once, and the receipt only gives the number.
A database links tables in the same way, and a link between tables is called a relationship. In this lesson, the member list becomes the customers table, and the receipts become the orders table.
Why split it into two tables
Imagine every order kept in one table, together with the buyer's name:
| id | customer_name | product |
|---|---|---|
| 1 | Budi | Laptop |
| 2 | Budi | Mouse |
| 3 | Siti | Monitor |
It looks tidy, but it has three problems:
- Budi's name is written twice. If Budi changes his name, you have to change every one of his order rows.
- Two customers who are both called Budi can't be told apart.
- Andi signed up but has never ordered. This table has no place for Andi, because each row is one order.
The fix: customers are stored in their own table, and each order only stores the customer's number.
customers
| id | name |
|---|---|
| 1 | Budi |
| 2 | Siti |
| 3 | Andi |
orders
| id | customer_id | product |
|---|---|---|
| 1 | 1 | Laptop |
| 2 | 1 | Mouse |
| 3 | 2 | Monitor |
| 4 | NULL | Webcam |
customer_id works like the member number on a receipt. A customer_id of 1 means "this order belongs to the row with id 1 in customers", which is Budi. The Webcam was bought by a guest with no account, so its customer_id is NULL (empty, no value yet): that order points at no customer. These two tables are used again in the JOIN and subquery lessons.
Three terms to remember:
- Primary key: the column whose value is unique in every row, here
id. At the minimarket, it's the member number. - Foreign key: a column in one table that holds the primary key of another table. Here it's
orders.customer_id(thecustomer_idcolumn of theorderstable). - The parent table is the table being pointed at, here
customers. The child table is the table that points, hereorders.
Writing a foreign key
The two tables are written with CREATE TABLE like this:
CREATE TABLE customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_id INTEGER, -- id of the customer who owns the order
product TEXT NOT NULL,
amount REAL,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
customersis created first, because it is the table being pointed at.customer_id INTEGER: the same type ascustomers.id. The name follows the usual habit: the table name in singular (customer, not customers) +_id.FOREIGN KEY (customer_id): the column in theorderstable that does the pointing.REFERENCES customers(id):customer_idpoints at theidcolumn of thecustomerstable.- The short form works too:
customer_id INTEGER REFERENCES customers(id). Pick one form, not both. - If every order must have an owner, add
NOT NULL:customer_id INTEGER NOT NULL. This example leavesNOT NULLout so a guest order like the Webcam may have no owner.
A foreign key guards the link
With a foreign key, the database helps make sure every customer_id really points at a customer that exists. Before you look at the table below, guess: the customers are only numbers 1 to 3, and you save an order for customer number 9. Is it saved, rejected, or is customer number 9 created automatically?
This is what SQLite answers in the Lab:
| Statement | Result |
|---|---|
INSERT INTO orders (customer_id, product, amount) VALUES (2, 'Keyboard', 50); |
saved, points at Siti |
INSERT INTO orders (customer_id, product, amount) VALUES (9, 'Headset', 75); |
rejected: FOREIGN KEY constraint failed |
DELETE FROM customers WHERE id = 1; |
rejected too: Budi still has orders |
INSERT INTO orders (customer_id, product, amount) VALUES (NULL, 'Cable', 5); |
saved: NULL isn't checked |
The order for customer number 9 is rejected, and no customer is created automatically. Without a foreign key, that order is saved anyway and becomes an "orphan": a row that points at a customer who doesn't exist.
Refusing to DELETE Budi is the default rule. Other options are written with ON DELETE after REFERENCES customers(id):
| Rule | When Budi is deleted | Good for |
|---|---|---|
no ON DELETE (default) |
refused | child rows that matter, such as orders that were paid |
ON DELETE CASCADE |
Budi's orders are deleted too | child rows that mean nothing without their parent, such as the items in a cart |
ON DELETE SET NULL |
Budi's orders stay, and their customer_id becomes NULL |
orders that must stay on record, such as the Cable order with no customer above |
One thing is specific to SQLite (used by the Lab, the Playground and the exercise): the foreign key check is only active after the command PRAGMA foreign_keys = ON;. Without that command, the foreign key is only recorded in the schema (the design of the tables), and it isn't checked. MySQL (with InnoDB, its default storage engine) and PostgreSQL check it right away.
Kinds of relationships
There are three kinds of relationships. They differ in how many rows of one table can be linked to one row of the other table.
| Relationship | Example | Where the foreign key goes |
|---|---|---|
| One-to-many | 1 customer has many orders | in the table on the "many" side: orders.customer_id |
| One-to-one | 1 user has 1 profile | in profiles.user_id, plus UNIQUE |
| Many-to-many | a student joins many clubs, a club has many students | in a linking table student_clubs with two foreign keys |
One-to-many is the most common. Another example: 1 teacher teaches many students, so the students table has a teacher_id column. Seen from the other side (many orders belong to 1 customer), it is sometimes called many-to-one, but it is the same relationship. In one-to-one, UNIQUE forbids repeated values, so each user can have only one profile. The linking table for many-to-many, a third table that stores pairs of a student and a club, is covered in the Schema Design lesson.
⚠️ An id column that doesn't really point anywhere
- Storing the name, not the id. A
customer_name TEXTcolumn inorderscopies the name into many rows, and two people with the same name get mixed up. - A
customer_idcolumn with noFOREIGN KEY. The number is stored, but the database doesn't know what it points at, so an order for customer number 9 is still saved. In the exercise, the checker looks at this link, not just the column name. - Writing the foreign key twice.
REFERENCESafter the column type plusFOREIGN KEY (...)at the end of the table makes two identical foreign keys. One is enough. - The wrong table name in
REFERENCES.REFERENCES customer(id)(no s) points at a table that doesn't exist.
TL;DR: Keep each kind of data in its own table, for example customers in customers and orders in orders. Then link them with a foreign key: a column in the child table (the table that points) that holds the primary key of the parent table (the table being pointed at). Here orders.customer_id (the customer_id column of orders) points at customers.id. Write FOREIGN KEY (customer_id) REFERENCES customers(id) once. The database then rejects an order for a customer who doesn't exist (FOREIGN KEY constraint failed; in SQLite after PRAGMA foreign_keys = ON). A customer_id that is NULL (empty) points at nobody and is still accepted, unless the column is NOT NULL. A relationship (a link between tables) can be one-to-many (1 customer has many orders, foreign key in the table on the many side), one-to-one, or many-to-many (through a linking table).
⚡ Store it once, point by id
Meaning: Customers are stored in their own table, customers, with the id column as the primary key. Each order in the orders table only stores the buyer's number in the customer_id column. So Budi's name is written once, and two customers who are both called Budi can't get mixed up, because their id values differ. This link between the two tables is called a relationship.
⚡ Write the foreign key
Write:
CREATE TABLE customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_id INTEGER,
product TEXT NOT NULL,
amount REAL,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
Meaning: customer_id is a foreign key: a column that holds another table's primary key. REFERENCES customers(id) means customer_id points at the id column of the customers table. That's why customers is created first.
⚡ The database stands guard
Guess first: customers only has customers number 1 to 3. You save an order with customer_id 9. What happens?
It's rejected: FOREIGN KEY constraint failed. No customer is created for you. An order with a NULL (empty) customer_id is still accepted, because it points at nobody.
Meaning: With a foreign key, the database checks every new customer_id: the number must exist in customers. In SQLite, this check is only active after the command PRAGMA foreign_keys = ON;.
⚡ Kinds of relationships
Meaning: The most common kind of relationship is one-to-many: 1 customer has many orders. The foreign key goes in the table on the "many" side, which is orders. There's also one-to-one (1 user has 1 profile), and many-to-many (1 student joins many clubs, 1 club has many students). Many-to-many uses a linking table: a third table that stores pairs of a student and a club.