TExcelTAD
Home › SQL › SQL FOREIGN KEY

SQL FOREIGN KEY

A foreign key is a column whose values must match the primary key (or a unique column) of another table. It protects referential integrity: an order cannot point to a customer that does not exist.

sql
CREATE TABLE child (
  ...
  parent_id INTEGER REFERENCES parent(parent_id)
);
-- or, as a table constraint:
--   FOREIGN KEY (parent_id) REFERENCES parent(parent_id)

The referenced table is the parent (customers), the referencing table the child (orders).

Foreign keys must be switched on in SQLite

For backwards compatibility, SQLite only enforces foreign keys after PRAGMA foreign_keys = ON; — once per connection. Every other database enforces them always.

sql · try it yourself
-- Off (the default): a bogus customer id is accepted
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (999, 4, '2025-10-21', 'processing');

PRAGMA foreign_keys = ON;

-- On: the same insert is rejected
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (998, 4, '2025-10-21', 'processing');
1 row affected.

Error: FOREIGN KEY constraint failed

Protecting the parent

With enforcement on, you also cannot delete a parent row that children still reference:

sql · try it yourself
PRAGMA foreign_keys = ON;

DELETE FROM customers WHERE customer_id = 24;   -- never ordered: fine
DELETE FROM customers WHERE customer_id = 2;    -- has orders: blocked
1 row affected.

Error: FOREIGN KEY constraint failed

ON DELETE and ON UPDATE actions

You can tell the database what to do with children when a parent row is deleted or its key changes:

Action Effect on children
NO ACTION / RESTRICT (default) the delete/update is refused
CASCADE children are deleted / updated too
SET NULL the foreign key column is set to NULL
SET DEFAULT it is set to its default value
sql · try it yourself
PRAGMA foreign_keys = ON;

CREATE TABLE carts (
  cart_id     INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(customer_id)
);
CREATE TABLE cart_items (
  cart_id    INTEGER NOT NULL REFERENCES carts(cart_id) ON DELETE CASCADE,
  product_id INTEGER NOT NULL REFERENCES products(product_id),
  quantity   INTEGER NOT NULL
);

INSERT INTO carts VALUES (1, 6), (2, 9);
INSERT INTO cart_items VALUES (1, 1, 2), (1, 18, 5), (2, 20, 1);

DELETE FROM carts WHERE cart_id = 1;

SELECT * FROM cart_items;
2 rows affected.

3 rows affected.

1 row affected.

cart_id | product_id | quantity
--------+------------+---------
2       | 20         | 1
(1 row)

Deleting cart 1 removed its two items automatically.

Finding broken references

If data was loaded while enforcement was off, PRAGMA foreign_key_check lists rows that violate their foreign keys:

sql · try it yourself
INSERT INTO products (name, category_id, price) VALUES ('Mystery Box', 99, 10);

SELECT "table", rowid, parent FROM pragma_foreign_key_check('products');
1 row affected.

table    | rowid | parent
---------+-------+-----------
products | 31    | categories
(1 row)

Foreign keys and joins

Foreign keys document how tables relate, and they are exactly the columns you join on: orders.customer_id = customers.customer_id. They do not create indexes automatically in most databases — index foreign key columns that you join or filter on often.

Test yourself

What does a foreign key guarantee?

  1. The column is unique
  2. Each value exists in the referenced table
  3. The column is indexed
  4. The column is not NULL

What must you run in SQLite before foreign keys are enforced?

  1. ENABLE FOREIGN KEYS
  2. PRAGMA foreign_keys = ON
  3. SET FOREIGN_KEY_CHECKS = 1
  4. Nothing

With ON DELETE CASCADE, what happens to children when the parent is deleted?

  1. Deletion is refused
  2. Children are deleted too
  3. Children's key is set to NULL
  4. Nothing