CodeBlanks Logo Icon CodeBlanks

Referential integrity

Learn referential integrity with FOREIGN KEY.

Referential integrity

Referential integrity ensures a foreign key points to a row in another table.

CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT,
  FOREIGN KEY (customer_id) REFERENCES customers(id)
);

Orders.customer_id → customers.id.

The table orders is created.

Referential integrity — details

A foreign key cannot point to a non-existent value. Deletes or updates can be restricted.

For example, if an order is inserted with a customer_id that doesn't exist in customers, the FOREIGN KEY stops it with an error.

Practice Referential integrity

Add a FOREIGN KEY on customer_id in orders.

Starter code

query.sql
-- referential integrity
ALTER TABLE orders

Sample solution

query.sql
ALTER TABLE orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id) REFERENCES customers(id)

Expected output

Tablo güncellendi

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Referential integrity: match the terms

Term Meaning
referential reference
FOREIGN KEY foreign key
REFERENCES references
orphan orphan row

2 FOREIGN KEY

Question
CONSTRAINT fk_customer ____ (customer_id) REFERENCES customers(id)
Answer
CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id)

Explanation: FOREIGN KEY is the right answer.

3 What does a foreign key ensure?

  • Speed
  • Sorting
  • Referential integrity Correct answer
  • Compression

Explanation: A foreign key ensures referential integrity.

All lessons in Intermediate