Sub topic 9
Linking Tables with `FOREIGN KEY`
Assume you know basic SELECT, INSERT, UPDATE, and DELETE statements. You should also understand that a table contains rows and columns, and that common data types describe values such as integers, text, and dates.
A foreign key is a column, or group of columns, that refers to a key in another table. It links related rows and protects referential integrity, which means references must point to existing rows.
For example, each order belongs to one customer. The orders.customer_id column can reference customers.customer_id.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
total_amount NUMERIC(10, 2) NOT NULL,
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id)
REFERENCES customers (customer_id)
);The referenced column is usually a primary key. It can also be protected by a suitable UNIQUE constraint. The foreign key and referenced key should use compatible data types.
How the relationship works
A customer row is the parent row. An order row is a child row. The child stores the key of its parent.
The database rejects an order that refers to a customer that does not exist:
INSERT INTO customers (customer_id, email)
VALUES (1, '[email protected]');
INSERT INTO orders (order_id, customer_id, total_amount)
VALUES (100, 1, 25.00); -- accepted
INSERT INTO orders (order_id, customer_id, total_amount)
VALUES (101, 999, 10.00); -- rejected: customer 999 does not existThe foreign key also affects changes to parent rows. If orders still reference customer 1, deleting that customer normally fails. This prevents an order from pointing to a missing customer.
Choosing referential actions
You can define what happens when a referenced parent row is deleted or updated.
| Action | Effect |
|---|---|
| `RESTRICT` | Rejects the parent change while child rows exist |
| `CASCADE` | Applies the deletion or update to related child rows |
| `SET NULL` | Sets the child key to `NULL` |
RESTRICT is often appropriate for customers and orders because historical orders should not disappear when a customer is removed. CASCADE fits dependent data, such as order items that should be removed with their order. Use SET NULL only when the relationship is optional, so the foreign-key column must allow NULL.
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL,
PRIMARY KEY (order_id, product_id),
CONSTRAINT fk_items_order
FOREIGN KEY (order_id)
REFERENCES orders (order_id)
ON DELETE CASCADE
);With this definition, deleting an order also deletes its items. That action should be deliberate because cascades can remove many rows.
Exercise
Why does inserting an order with customer_id 999 fail when no customer has that ID?
Show answer
The foreign key requires every non-NULL orders.customerid value to match an existing customers.customerid value.