Sub topic 7
Linking Tables with a Foreign Key
Assume you know basic SELECT, INSERT, UPDATE, and DELETE, can create tables, and understand rows, columns, data types, and NULL. This chapter uses PostgreSQL-style SQL.
What a foreign key does
A foreign key is a column, or group of columns, whose values must match a key in another table. The table containing the foreign key is the child table. The table containing the referenced key is the parent table.
For example, one customer can place many orders. Each order belongs to one customer. The orders.customer_id foreign key links each order to customers.customer_id.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL,
ordered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id)
REFERENCES customers (customer_id)
);The referenced column must identify rows. It is normally a primary key or a column with a UNIQUE constraint. The foreign key does not copy the customer’s name or email. It stores the customer’s key and points to the parent row.
What the database rejects
Referential integrity is the rule that relationships remain valid. Because customer_id is NOT NULL, every order must name a customer. Because it is also a foreign key, that customer must already exist.
INSERT INTO customers (email, name)
VALUES ('[email protected]', 'Ana');
INSERT INTO orders (customer_id)
SELECT customer_id
FROM customers
WHERE email = '[email protected]';
-- Fails: no customer has this key.
INSERT INTO orders (customer_id)
VALUES (999);The database also protects referenced rows. With the default NO ACTION behavior, deleting a customer fails while orders still refer to that customer.
-- Fails if customer 1 still has orders.
DELETE FROM customers
WHERE customer_id = 1;An update to a parent key can fail for the same reason. In practice, primary keys are usually stable, so applications update descriptive columns such as name instead.
| Operation | Result when related rows exist |
|---|---|
| Insert a child with a missing parent key | Rejected |
| Delete a referenced parent | Rejected by default |
| Change a referenced parent key | Usually rejected by default |
Choosing the relationship behavior
You can define a referential action when a parent row is deleted or its key changes.
NO ACTIONchecks the relationship and rejects the operation if children remain.RESTRICTrejects the operation immediately.CASCADEdeletes or updates related child rows.SET NULLclears the child key, so the foreign key must allowNULL.SET DEFAULTreplaces the child key with its default value, which must still be valid.
Use CASCADE only when child rows have no meaning without the parent. For example, order items can usually be deleted when an order is deleted. Customer orders normally should not be deleted when a customer account is removed.
Exercise
Exercise
Why does inserting an order with customer_id 999 fail when no customer has that primary key?
Show answer
The foreign key requires every non-NULL child value to match an existing key in the parent table.