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

Steps for a new table

  1. Create the "parent" table that will be pointed to:
CREATE TABLE customers (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
  1. 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".

  1. 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

  1. Add a customer: INSERT INTO customers (name) VALUES ('Ana');
  2. Add a valid order: INSERT INTO orders (customer_id, item) VALUES (1, 'Lamp'); This should work.
  3. 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:

OptionEffectWhen to use
(default)Refuse to delete a customer who still has ordersSafest for beginners
ON DELETE CASCADEDelete the orders tooChild rows make no sense without the parent
ON DELETE SET NULLEmpty the order's customer_idThe 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.

Related pages on this site