Sub topic 9
Linking tables with FOREIGN KEY
This chapter assumes you can write basic SELECT, INSERT, UPDATE, and DELETE statements. It also assumes you know what a primary key and a UNIQUE constraint do, and that you can read a simple CREATE TABLE statement.
What a foreign key does
A foreign key is a constraint that ties a column (or several columns) in one table to the key of another table. The table holding the foreign key is the child table. The table it points to is the parent table.
The rule is simple: every non-NULL value in the child's foreign key columns must match an existing value in the parent's referenced columns. This guarantee is called referential integrity. Without it, an order could point to a customer who does not exist, and queries that join the two tables would silently lose rows.
Basic syntax
Here is the schema from the earlier chapters. The customers table is the parent, and orders is the child.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
total_amount NUMERIC(10, 2) NOT NULL,
CONSTRAINT pk_orders PRIMARY KEY (order_id),
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
ON DELETE RESTRICT,
CONSTRAINT ck_orders_total CHECK (total_amount >= 0),
CONSTRAINT ck_orders_status
CHECK (status IN ('new', 'paid', 'shipped', 'cancelled'))
);The foreign key clause has three parts:
FOREIGN KEY (customer_id)names the child column.REFERENCES customers (customer_id)names the parent table and column.ON DELETE RESTRICTsays what happens when someone deletes a parent row that still has children.
Create the parent table first. The database must know about customers before orders can refer to it.
Requirements on the parent column
The referenced column must be guaranteed unique. In practice it is the parent's primary key, but a column or column set with a UNIQUE constraint also works. If the parent column allowed duplicates, a child value could match several parent rows and the reference would be ambiguous.
The child column's data type must be compatible with the parent's. Use the same type, such as INTEGER to INTEGER. Some systems reject mismatches, and others convert silently and slow down joins.
If you omit the column list after REFERENCES customers, most systems default to the parent's primary key. Naming the column is clearer and safer.
What the constraint rejects
A foreign key is checked in three situations:
- Inserting or updating a child row to a value that has no parent.
- Deleting a parent row that still has children.
- Updating a parent key that children still reference.
The first case is the one most people meet. This statement fails because no customer 9999 exists:
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Ada Lovelace');
INSERT INTO orders (customer_id, total_amount)
VALUES (9999, 10.00);PostgreSQL reports an error like this:
ERROR: insert or update on table "orders" violates foreign key constraint "fk_orders_customer"
DETAIL: Key (customer_id)=(9999) is not present in table "customers".The error names the constraint. This is why naming constraints is worth the effort: fk_orders_customer tells you which rule failed. Without a name, the database invents one.
The same constraint rejects the second case:
DELETE FROM customers WHERE customer_id = 1;This fails once customer 1 has an order, because of ON DELETE RESTRICT.
NULL in a foreign key column
A foreign key column that allows NULL can hold NULL, and the database does not check NULL against the parent. NULL means "no reference". This is useful for optional relationships. An employees.manager_id column can be NULL for the top of the hierarchy.
If the relationship is required, add NOT NULL, as orders.customer_id does. The foreign key guarantees that a value, if present, is valid. Only NOT NULL guarantees a value is present.
With a composite foreign key, the default matching behavior differs by system when only some columns are NULL. PostgreSQL's default (MATCH SIMPLE) skips the check if any column is NULL. To avoid surprises, declare every column of a composite foreign key NOT NULL.
Column-level syntax
For a single-column key, you can write the reference inline on the column:
CREATE TABLE invoices (
invoice_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders (order_id),
issued_on DATE NOT NULL DEFAULT CURRENT_DATE
);This is shorter, but it gives the constraint a system-generated name. Composite foreign keys require the table-level form.
Foreign keys in a junction table
Many-to-many relationships need a junction table with two foreign keys. Each order can contain many products, and each product can appear in many orders.
CREATE TABLE products (
product_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price NUMERIC(10, 2) NOT NULL CHECK (price >= 0)
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders (order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (product_id)
);The composite primary key (order_id, product_id) allows each product once per order. Each column also carries its own foreign key. Deleting an order removes its items because of ON DELETE CASCADE. Deleting a product that appears in an order is rejected, because the second foreign key uses the default action.
Referential actions have their own chapter, so this chapter only notes the default: if you write no ON DELETE clause, the database uses NO ACTION, which rejects the delete.
Self-referencing foreign keys
A table can reference itself. This models hierarchies such as employees and managers.
CREATE TABLE employees (
employee_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
full_name VARCHAR(100) NOT NULL,
manager_id INTEGER,
CONSTRAINT fk_employees_manager
FOREIGN KEY (manager_id) REFERENCES employees (employee_id)
);manager_id is nullable so the top-level employee can have no manager. You insert the top employee first, then insert the others pointing at an existing row.
Common errors and edge cases
| Symptom | Cause | Fix |
|---|---|---|
| Error creating the child table: referenced table does not exist | The parent table was not created first | Reorder the `CREATE TABLE` statements |
| Error: no unique constraint matches the referenced columns | The parent column is not a primary key or `UNIQUE` | Add a primary key or `UNIQUE` constraint to the parent column |
| Error about incompatible types | Child and parent column types differ | Make the types match |
| Inserts fail during bulk loads | Children loaded before their parents | Load parents first |
| Cannot drop the parent table | A child's foreign key still depends on it | Drop the child first, or drop the constraint |
| Foreign keys appear to be ignored in MySQL | The table uses an engine without foreign key support | Use InnoDB |
| Foreign keys appear to be ignored in SQLite | Enforcement is off by default | Run `PRAGMA foreign_keys = ON;` on each connection |
The last two rows are the main enforcement caveats. SQLite accepts the foreign key syntax but does not enforce it unless you turn it on for each connection. Older MySQL setups using MyISAM parse the clause and then ignore it. A schema can look protected and not be.
Foreign keys and performance
The parent's referenced column is indexed already, because primary key and UNIQUE constraints create an index. The child's foreign key column is not indexed automatically in PostgreSQL or Oracle. MySQL's InnoDB does create one. Without an index on the child column, a parent delete must scan the child table to check for children, and joins from parent to child are slower. Add an index when the child table is large:
CREATE INDEX ix_orders_customer_id ON orders (customer_id);Summary of the rules
- A foreign key requires each non-NULL child value to exist in the parent's unique columns.
- Create parents before children.
- Add
NOT NULLwhen the relationship is required. - Name the constraint so errors are readable.
- Check that your database actually enforces foreign keys.
Exercise
A table reviews has a column product_id INTEGER REFERENCES products (product_id) with no NOT NULL. Can you insert a review with product_id set to NULL? Can you insert one with product_id set to 5000 when no product 5000 exists? What change would make every review require a product?
Show answer
The NULL insert succeeds, because a foreign key does not check NULL values. The insert with 5000 fails with a foreign key violation, because no matching parent row exists. Adding NOT NULL to the productid column (productid INTEGER NOT NULL REFERENCES products (product_id)) makes a product required for every review.
Exercise
You run CREATE TABLE shipments (shipment_id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL REFERENCES orders (order_id)); before orders exists. What happens, and how do you fix it?
Show answer
The statement fails because the referenced table orders does not exist yet. Create orders (and customers, which orders depends on) first, then create shipments.