24/07/2025
🔗 FOREIGN KEY with ON DELETE Options
When you define a foreign key, you can specify what should happen to the child table rows when a row in the parent table is deleted.
🧨 1. ON DELETE CASCADE
👉 Automatically deletes matching rows in the child table when the parent row is deleted.
🧯 2. ON DELETE SET NULL
👉 Automatically sets the foreign key column(s) in the child table to NULL when the parent row is deleted.
✅ Example Scenario
Let’s say we have:
A parent table: departments
A child table: employees (each employee belongs to a department)
🔧 Step-by-Step SQL Example:
🔹 Step 1: Create Parent Table
CREATE TABLE departments (
dept_id NUMBER PRIMARY KEY,
dept_name VARCHAR2(100)
);
🔹 Step 2: Create Child Table with ON DELETE CASCADE
CREATE TABLE employees (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(100),
dept_id NUMBER,
CONSTRAINT emp_dept_fk FOREIGN KEY (dept_id)
REFERENCES departments(dept_id)
ON DELETE CASCADE
);
✅ Now if you delete a row from departments, all related rows in employees will be deleted automatically.
🔹 Step 3: Create Child Table with ON DELETE SET NULL
If instead, you want to keep the employee, but set dept_id to NULL when the department is deleted:
CREATE TABLE employees (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(100),
dept_id NUMBER,
CONSTRAINT emp_dept_fk FOREIGN KEY (dept_id)
REFERENCES departments(dept_id)
ON DELETE SET NULL
);
✅ Now when a department is deleted, affected employees’ dept_id will become NULL.
🔍 Visual Summary:
Option Result when parent row is deleted
ON DELETE CASCADE Deletes matching child rows
ON DELETE SET NULL Sets foreign key column(s) in child to NULL