CASCADE
- SQL course
- Beginner
- Lesson 98/115
- 4 min
Learn how a child table reacts when the parent changes.
FOREIGN KEY
With FOREIGN KEY you link a column to another table's primary key. It keeps referential integrity.
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);Orders.customer_id references customers.id.
The table orders is created.
FOREIGN KEY — details
FOREIGN KEY blocks adding an order for a non-existent customer. ON DELETE decides what happens when the customer is removed.
Practice FOREIGN KEY
Create orders with id INT PRIMARY KEY and customer_id INT FOREIGN KEY REFERENCES customers(id).
Starter code
-- related table
CREATE TABLE ordersSample solution
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id)
)Expected output
Tablo oluşturuldu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does FOREIGN KEY ensure?
- Referential integrity Correct answer
- Speed
- Uniqueness
- Sorting
Explanation: FOREIGN KEY ensures referential integrity.
2 Add relation
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,
____ (customer_id) REFERENCES customers(id)
);
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
Explanation: FOREIGN KEY is the right answer.
3 CASCADE: match the terms
| Term | Meaning |
|---|---|
FOREIGN KEY |
relation |
PRIMARY KEY |
primary |
REFERENCES |
reference |
UNIQUE |
unique |