Foreign key ON DELETE behavior in SQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When a row is deleted in a table with foreign keys, the database must handle related rows in other tables.
We want to understand how the work grows when deleting rows with different ON DELETE rules.
Analyze the time complexity of deleting a row with foreign key constraints.
-- Parent table
CREATE TABLE departments (
id INT PRIMARY KEY,
name VARCHAR(50)
);
-- Child table with foreign key
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(id) ON DELETE CASCADE
);
-- Deleting a department row
DELETE FROM departments WHERE id = 10;
This code deletes a department and triggers actions on employees linked by foreign key with ON DELETE CASCADE.
Look at what the database does when deleting a row with ON DELETE CASCADE.
- Primary operation: The database searches the child table for all rows referencing the deleted parent row.
- How many times: It checks each child row that matches the foreign key condition, potentially many rows.
As the number of child rows linked to the parent grows, the work to delete grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 child rows | 10 checks and deletes |
| 100 child rows | 100 checks and deletes |
| 1000 child rows | 1000 checks and deletes |
Pattern observation: The work grows roughly in direct proportion to the number of child rows linked to the deleted parent.
Time Complexity: O(n)
This means the time to delete grows linearly with the number of related child rows that must be handled.
[X] Wrong: "Deleting a parent row is always a quick, single-step operation regardless of child rows."
[OK] Correct: The database must find and process all child rows affected by the foreign key rule, which takes more time as child rows increase.
Understanding how foreign key deletions scale helps you explain database behavior clearly and shows you know how data relationships affect performance.
"What if the foreign key used ON DELETE SET NULL instead of CASCADE? How would the time complexity change?"
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
