What if deleting one record could magically clean up all related data without you lifting a finger?
Why Foreign key ON DELETE behavior in SQL? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have two lists on paper: one with customers and another with their orders. When a customer leaves, you have to manually find and erase all their orders from the orders list to keep things tidy.
This manual cleanup is slow and easy to forget. If you miss deleting some orders, your lists become messy and confusing, causing mistakes and wasted time.
Using foreign key ON DELETE behavior in databases automates this cleanup. When you delete a customer, the database automatically deletes or updates related orders, keeping data neat without extra work.
DELETE FROM customers WHERE id = 5; -- Then manually delete orders: DELETE FROM orders WHERE customer_id = 5;
ALTER TABLE orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id)
REFERENCES customers(id)
ON DELETE CASCADE;
DELETE FROM customers WHERE id = 5; -- orders auto deletedThis lets you trust your data stays consistent and clean automatically, saving time and avoiding errors.
In an online store, when a user account is deleted, all their shopping cart items and wishlists are removed automatically, preventing leftover data clutter.
Manual deletion of related data is slow and error-prone.
Foreign key ON DELETE automates cleanup of related records.
This keeps your database consistent and saves you effort.
Practice
ON DELETE CASCADE option do in a foreign key constraint?Solution
Step 1: Understand ON DELETE CASCADE behavior
This option means that when a parent row is deleted, all child rows linked by the foreign key are also deleted automatically.Step 2: Compare with other options
Other options like RESTRICT block deletion, and SET NULL clears the foreign key, so only CASCADE deletes child rows.Final Answer:
Deletes all related child rows automatically when the parent row is deleted. -> Option AQuick Check:
ON DELETE CASCADE = delete related rows [OK]
- Confusing CASCADE with RESTRICT
- Thinking CASCADE sets foreign keys to NULL
- Assuming CASCADE does nothing
ON DELETE SET NULL in SQL?Solution
Step 1: Identify the syntax for ON DELETE SET NULL
The correct syntax includes the phraseON DELETE SET NULLafter the foreign key reference.Step 2: Match options with syntax
FOREIGN KEY (child_id) REFERENCES parent(id) ON DELETE SET NULL exactly matches the required syntax for setting foreign keys to NULL on parent deletion.Final Answer:
FOREIGN KEY (child_id) REFERENCES parent(id) ON DELETE SET NULL -> Option BQuick Check:
ON DELETE SET NULL syntax = FOREIGN KEY (child_id) REFERENCES parent(id) ON DELETE SET NULL [OK]
- Choosing CASCADE instead of SET NULL
- Confusing RESTRICT and NO ACTION
- Missing ON DELETE clause
CREATE TABLE parent (id INT PRIMARY KEY);
CREATE TABLE child (id INT PRIMARY KEY, parent_id INT, FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE RESTRICT);
INSERT INTO parent VALUES (1);
INSERT INTO child VALUES (10, 1);
What happens if you run
DELETE FROM parent WHERE id = 1;?Solution
Step 1: Understand ON DELETE RESTRICT effect
RESTRICT prevents deleting a parent row if any child rows reference it.Step 2: Apply to given data
Since child row with parent_id=1 exists, deleting parent id=1 is blocked.Final Answer:
The delete fails because the child row exists and ON DELETE RESTRICT blocks it. -> Option DQuick Check:
ON DELETE RESTRICT blocks delete if children exist [OK]
- Assuming CASCADE behavior with RESTRICT
- Thinking child foreign key becomes NULL
- Believing delete always succeeds
ALTER TABLE child ADD CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE SET NULL;
But when you delete a parent row, the child row's
parent_id does not become NULL. What is the likely problem?Solution
Step 1: Check column nullability
ON DELETE SET NULL requires the foreign key column to allow NULL values.Step 2: Identify the cause
Ifparent_idis NOT NULL, the database cannot set it to NULL, so it leaves it unchanged.Final Answer:
Theparent_idcolumn is NOT NULL, so it cannot be set to NULL. -> Option CQuick Check:
SET NULL needs nullable foreign key column [OK]
- Assuming syntax error causes issue
- Thinking SET NULL requires CASCADE
- Believing manual delete is always needed
CREATE TABLE orders (order_id INT PRIMARY KEY);
CREATE TABLE order_items (item_id INT PRIMARY KEY, order_id INT, FOREIGN KEY (order_id) REFERENCES orders(order_id) ON DELETE CASCADE);
You want to delete an order and all its items safely. However, sometimes
order_items.order_id can be NULL for items not linked to any order. What is the best ON DELETE behavior to use for the foreign key to avoid errors and keep data consistent?Solution
Step 1: Identify the goal
You want to delete an order and automatically delete all its related items safely.Step 2: Evaluate ON DELETE CASCADE
CASCADE deletes all child rows (order_items) where order_id matches the deleted order, achieving the goal automatically.Step 3: Handle NULL values
Items with NULL order_id are not referencing any order, so CASCADE leaves them untouched, maintaining consistency without errors.Final Answer:
ON DELETE CASCADE, because it deletes all linked items automatically. -> Option AQuick Check:
Delete order + linked items safely = ON DELETE CASCADE [OK]
- Choosing SET NULL, which orphans items instead of deleting
- Using RESTRICT, blocking necessary deletes
- Picking NO ACTION, requiring manual item deletes
