Constraint management
- SQL course
- Beginner
- Lesson 99/115
- 4 min
Add and drop constraints.
ON DELETE and ON UPDATE
With ON DELETE and ON UPDATE you set FOREIGN KEY behavior. Options are CASCADE, SET NULL and RESTRICT.
FOREIGN KEY (customer_id) REFERENCES customers(id)
ON DELETE CASCADEWhen the customer is deleted the orders are deleted too.
ON DELETE and ON UPDATE — details
CASCADE deletes/updates linked rows. SET NULL empties the linked column. RESTRICT blocks the delete. The default is RESTRICT.
Practice ON DELETE and ON UPDATE
Add customer_id FOREIGN KEY REFERENCES customers(id) ON DELETE CASCADE to orders.
Starter code
-- add relation
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,Sample solution
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
)Expected output
Tablo oluşturuldu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Cascade
FOREIGN KEY (cid) REFERENCES c(id) ON DELETE ____;
FOREIGN KEY (cid) REFERENCES c(id) ON DELETE CASCADE;
Explanation: CASCADE is the right answer.
2 Constraint management: match the terms
| Term | Meaning |
|---|---|
CASCADE |
cascade |
SET NULL |
set null |
RESTRICT |
block |
FOREIGN KEY |
relation |
3 What does ON DELETE CASCADE do?
- Sets the related rows to empty
- Also deletes the related rows Correct answer
- Keeps the related rows
- Nothing
Explanation: CASCADE deletes linked rows too.