Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
Python : __delete__ vs __del__
Next article icon

PL/SQL ON DELETE CASCADE

Last Updated : 11 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The ON DELETE CASCADE option in PL/SQL is used to automatically delete rows from a child table when the corresponding row in the parent table is deleted. This feature helps maintain referential integrity by ensuring that related records in child tables are removed in sync with changes in the parent table.

This is particularly useful in relational databases where entities are linked, and deleting a parent record should also remove its dependent records. This article will explore the concept of ON DELETE CASCADE in PL/SQL, and explain examples with their syntax, and output.

PL/SQL ON DELETE CASCADE

The ON DELETE CASCADE constraint is applied to foreign key relationships to specify that when a row in the parent table is deleted, all corresponding rows in the child table should be automatically deleted. This ensures consistency and prevents orphaned records.

Syntax:

CREATE TABLE child_table (

child_id INT PRIMARY KEY,

parent_id INT,

FOREIGN KEY (parent_id) REFERENCES parent_table(parent_id) ON DELETE CASCADE

);

Explanation:

This syntax defines a child_table with a primary key column (child_id) and a foreign key column (parent_id). The foreign key ensures referential integrity by linking records in child_table to parent_table, and the ON DELETE CASCADE option ensures that any related child records are automatically removed when the corresponding parent record is deleted.

Examples of PL/SQL ON DELETE CASCADE

The ON DELETE CASCADE clause is used in PL/SQL to automatically delete related records in a child table when the corresponding record in the parent table is deleted.

This ensures referential integrity by preventing orphaned records in the child table.

Table 1: Departments

The departments table is created with two columns: dept_id, which is the primary key, and dept_name, which stores the department names. The dept_id uniquely identifies each department.

The CREATE TABLE statement creates the departments table with dept_id as the primary key. The INSERT INTO statements add three records into the departments table, representing three departments: HR, Finance, and IT.

Query:

CREATE TABLE departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50)
);

INSERT INTO departments (dept_id, dept_name) VALUES (1, 'HR');
INSERT INTO departments (dept_id, dept_name) VALUES (2, 'Finance');
INSERT INTO departments (dept_id, dept_name) VALUES (3, 'IT');

Output:

dept_iddept_name
1HR
2Finance
3IT

Explanation:

  • The output will be the successful creation of the departments table and the insertion of three records into it, with dept_id values 1, 2, and 3 corresponding to the HR, Finance, and IT departments respectively.
  • The output is not directly visible in the database but can be confirmed by querying the departments table.

Table 2: Employees

The employees table is created with a foreign key constraint on dept_id, which references the departments table.

The ON DELETE CASCADE clause ensures that if a department is deleted from the departments table, all related records in the employees table are automatically deleted. The INSERT statements add five employees, each linked to a department by dept_id

Query:

CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id) ON DELETE CASCADE
);

INSERT INTO employees (emp_id, emp_name, dept_id) VALUES (1, 'Alice', 1);
INSERT INTO employees (emp_id, emp_name, dept_id) VALUES (2, 'Bob', 2);
INSERT INTO employees (emp_id, emp_name, dept_id) VALUES (3, 'Charlie', 3);
INSERT INTO employees (emp_id, emp_name, dept_id) VALUES (4, 'David', 1);
INSERT INTO employees (emp_id, emp_name, dept_id) VALUES (5, 'Eve', 2);

Output:

emp_idemp_namedept_id
1Alice1
2Bob2
3Charlie3
4David1
5Eve2

Explanation:

  • The output displays a table of employees along with their corresponding department IDs. Each emp_id is unique, showing the employee's name (emp_name) and the department they belong to (dept_id).
  • The data reflects the successful insertion of employee records, with departments linked by foreign key constraints.

Example 1: Delete Department and Automatically Remove Employees

Deleting a department will automatically trigger the deletion of all employees associated with that department due to the ON DELETE CASCADE clause in the employees table.

In this case, employees "Alice" and "David," who were linked to dept_id = 1 (HR department), are also deleted. This action ensures referential integrity, preventing orphaned records in the employees table that would no longer have a corresponding department.

Query:

DELETE FROM departments WHERE dept_id = 1;

Output:

emp_idemp_namedept_id
2Bob2
3Charlie3
5Eve2

Explanation:

  • When we delete the department with dept_id = 1 from the departments table, the ON DELETE CASCADE clause automatically removes all employees in the employees table associated with that department.
  • All employees linked to the deleted department are removed.
  • The department no longer exists in the departments table.

Example 2: Deleting Multiple Departments

When deleting multiple departments, the cascade delete feature ensures that all employees related to those departments are also removed.

In this query, deleting departments with dept_id values 1 and 2 triggers the ON DELETE CASCADE action in the employees table. This operation ensures that the database remains consistent and no employees are left without a valid department.

Query:

DELETE FROM departments WHERE dept_id IN (1, 2);

Output:

dept_iddept_name
3IT

Explanation:

  • Employees associated with the deleted departments are automatically removed.
  • Specifically, employees "Alice," "David," "Bob," and "Eve" are deleted because their associated departments (HR and Finance) were removed
  • Only departments not targeted by the delete operation remain.
  • Only the IT department and its associated employee "Charlie" remain in the respective tables.

Example 3: Attempt to Delete a Non-Existent Department

If we try to delete a department that doesn't exist, the ON DELETE CASCADE clause has no effect because there are no related records to delete.

In this scenario, attempting to delete a department with dept_id = 4 results in no changes because this department does not exist in the departments table. The ON DELETE CASCADE clause has no effect since there are no related records in the employees table to delete.

Query:

DELETE FROM departments WHERE dept_id = 4;

Output:

dept_iddept_name
1HR
2Finance
3IT

Explanation:

  • No changes occur in the tables since the specified department does not exist.
  • Data integrity is maintained without any unintended deletion
  • Consequently, both the departments and employees tables remain unchanged, preserving data integrity without any unintended deletions.
  • This ensures that only existing records are targeted by delete operations.

Conclusion

The ON DELETE CASCADE option is a valuable feature in SQL that maintains referential integrity by ensuring that child records are automatically deleted when their parent record is removed. This option simplifies data management and prevents orphaned records, making it easier to keep related data consistent.


Next Article
Python : __delete__ vs __del__
author
prathamsahani2020
Improve
Article Tags :
  • Databases
  • PL/SQL

Similar Reads

  • PL/SQL DELETE JOIN
    In database management, removing specific records from a table is a common task especially when cleaning or updating data. One useful technique is the DELETE JOIN which allows us to delete records from one table based on conditions involving another table. In this article, we will explore PL/SQL DEL
    4 min read
  • Cascade in SQL
    Structured Query Language (SQL) is the backbone of relational database management systems, Enabling developers to manipulate and manage data effectively. One crucial feature for maintaining data integrity in SQL is the CASCADE operation, which simplifies handling relationships between parent and chi
    4 min read
  • SQL DELETE JOIN
    The SQL DELETE JOIN statement is a powerful feature that allows us to delete rows from one table based on conditions involving another table. This is particularly useful when managing relationships between tables in a database. For example, we may want to delete rows in a "Library Books" table where
    4 min read
  • SQLAlchemy Cascading Deletes
    SQLAlchemy is a powerful ORM (Object-Relational Mapping) library for Python that allows developers to interact with relational databases using Python objects. It provides a rich set of tools for querying, updating, and manipulating data, making it a popular choice for building web applications and o
    4 min read
  • Python : __delete__ vs __del__
    Both __delete__ and __del__ are dunder or magic methods in Python. Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. __del__ __del__ is a des
    2 min read
  • MySQL DELETE JOIN
    MySQL is an open-source, user-friendly, powerful, and popular choice, relational database management system. When maintaining and modifying data, tables usually interact in a complex way. MySQL's DELETE JOIN function is one of its most powerful functions. MySQL DELETE JOIN is explored in detail in t
    4 min read
  • How to Delete Column in SQL
    In SQL, deleting a column from an existing table is a straightforward process, but it's important to understand the implications and the correct syntax involved. While there is no direct DELETE COLUMN command in SQL, we can achieve this by using the ALTER TABLE command combined with DROP COLUMN. In
    5 min read
  • When to Use ON UPDATE CASCADE in PL/SQL?
    In Oracle PL/SQL, managing the update of related records in child tables can be challenging, especially when dealing with complex data relationships. The ON UPDATE CASCADE option in Oracle provides a powerful solution to automate the update of child records whenever the corresponding parent record i
    4 min read
  • PL/SQL DELETE Statement
    In PL/SQL(Procedural Language/Structured Query Language), the DELETE statement is the powerful command used to remove one or more records from the database table. It is an essential part of database management and enables the users to efficiently manage and maintain the data integrity by selectively
    7 min read
  • Difference Between DELETE and DROP in SQL
    In SQL, the DELETE and DROP commands are essential for managing data in a database, but they serve different purposes. While both are used to remove data, their functionality varies significantly. The DELETE command is designed to remove specific rows (tuples) or all rows from a table while preservi
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences