How to Add a Foreign Key Between Two Tables
A foreign key tells the database that a column in one table must match a primary key in another. It stops mistakes like an order for a customer who does not exist. This how-to adds one and proves it works.
What you need
- a practice database (SQLite, PostgreSQL or MySQL)
- two related tables, or the willingness to create them below
- permission to change the tables
Steps for a new table
- Create the "parent" table that will be pointed to:
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
- Create the "child" table with a foreign key:
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers(id),
item TEXT NOT NULL
);
REFERENCES customers(id) is the foreign key. NOT NULL adds "every order must have a customer".
- SQLite only: turn on foreign key checks for your session, because they are off by default:
PRAGMA foreign_keys = ON;
Programs using SQLite must run this on every new connection.
Steps for an existing table
In PostgreSQL and MySQL you can add a foreign key to a table that already exists:
ALTER TABLE orders
ADD CONSTRAINT orders_customer_fk
FOREIGN KEY (customer_id) REFERENCES customers(id);
If existing rows already break the rule, this fails. Find them first:
SELECT * FROM orders
WHERE customer_id NOT IN (SELECT id FROM customers);
Fix or remove those rows, then try again. SQLite cannot add a foreign key to an existing table with ALTER TABLE; the usual approach there is to create a new table with the key, copy the rows across and rename it.
How to check it worked
- Add a customer:
INSERT INTO customers (name) VALUES ('Ana'); - Add a valid order:
INSERT INTO orders (customer_id, item) VALUES (1, 'Lamp');This should work. - Add an invalid order:
INSERT INTO orders (customer_id, item) VALUES (99, 'Rug');This should fail with an error mentioning a foreign key constraint.
If step 3 succeeds in SQLite, you forgot the PRAGMA.
Choosing what happens on delete
What should happen to orders when their customer is deleted? You choose when you create the key:
| Option | Effect | When to use |
|---|---|---|
| (default) | Refuse to delete a customer who still has orders | Safest for beginners |
ON DELETE CASCADE | Delete the orders too | Child rows make no sense without the parent |
ON DELETE SET NULL | Empty the order's customer_id | The child can exist on its own; column must allow NULL |
Example: REFERENCES customers(id) ON DELETE CASCADE.
A tip for later
Looking up "all orders for one customer" is a very common query. Adding an index on orders.customer_id makes it fast as the table grows. MySQL creates one automatically for foreign keys; PostgreSQL and SQLite do not.
Next steps
See the idea drawn out in a picture guide to keys linking two tables, then read both tables together with a JOIN.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.