Introduction to MySQL ON DELETE CASCADE
MySQL ON DELETE CASCADE is a MySQL referential action for a MySQLforeign key that permits to remove records automatically from the child-related tables when the main parental table data is deleted.
This MySQL ON CASCADE statement query is responsible to show reference method where a child table data related to the parent table having Primary and Foreign keys executes to process the query to delete the data from both correlated tables.
It means that if we delete any data or column values in the parental table then, with referential action the related data or column values with a foreign key in the sub-table will also be removed spontaneously.
We use the following syntax for the MySQL ON DELETE CASCADEfor foreign key using CREATE TABLE:
CREATE TABLE ChildTable_Name(Col1 Data_Type [NOT NULL | PRIMARY KEY | AUTO_INCREMENT],.., ColNDate_Type [NOT NULL | NULL]
FOREIGN KEY (Col1_Child, …, ColN_Child)
REFERENCES ParentTable_Name (Col1_Parent, …., ColN_Parent)
ON DELETE CASCADE);
Here, the terms used are explained below:
- A foreign key for a MySQL ON DELETE CASCADE can be generated with the help of either using MySQL CREATE TABLE or MySQL ALTER TABLE statements.
- ChildTable_Name: It denotes the name of the child table related to the parent table.
- Col1,..,ColN: These are the column names that we want to create with the respective data type in the table. It has a default value as NULL when we do not provide any data type but we need to add some data type for the proper execution of query either NULL or NOT NULL.
- Col1_Child,…,ColN_Child: These are the columns of the child table which has reference to Primary key in the parental table.
- ParentTable_Name: This is the name of the parent table to be used in the query statement whose primary keys are linked to being used in the child table.
- Col1_Parent,…..,ColN_Parent: These are the parent table columns which holds Primary keys to which the foreign key will be associated
- ON DELETE CASCADE: This MySQL Keyword is responsible to make changes on the child table when the parent table is affected.
- CASCADE: It denotes that when the parent data is affected then, the child data is also altered accordingly since it is used in aggregation to ON DELETE or ON UPDATE.
How ON DELETE CASCADE works in MySQL?
- In MySQL, the parent table comprises the original key values in a table whereas the child table is defined as the linked table that refers to the main key values in the parental table in a database.
- Supposing we have created two MySQL tables person(ID, Name, Address) and Employee(EmpID, ID, Profile, Contact). In the MySQL database structure model, each person occupies either single or multiple employee profiles. However, every employee profile belongs to just one single person in the table relation. An employee profile will not be existent lacking a person.
- Hence, we can conclude that the relation between the person and employee tables is distinct to various i.e. (1:N)
- Again, assume that when you cancel a row in the person table then, you also desire to remove the rows from the employee table that is associated with the Primary key record in the person table.
- For instance, if you remove the person with id 1, the employee profiles that reference to this id will also be needed to remove so, in this case, we will apply with DELETE statement the MySQL ON DELETE CASCADE for a foreign key.
- An important thing is to be noticed that MySQL ON DELETE CASCADE works with the storage engines that support foreign keys such as InnoDB but it may not work in MyISAM type engine.
Examples of MySQL ON DELETE CASCADE
Let us consider the following examples to demonstrate the use of MySQL ON DELETE CASCADEfor a foreign key for referential works using the CREATE, SELECT like Table statements:
Example #1 – Creating a parent table
We are creating a main table with Primary key using the below query:
CREATE TABLE Building (Build_Num int AUTO_INCREMENT PRIMARY KEY, Build_Name varchar(255) NOT NULL, Build_Address varchar(255) NOT NULL)ENGINE = InnoDB;
Example #2 – Creating a child table
We will also create a sub-table for a foreign key referential action and implementing the MySQL ON DELETE CASCADE with CREATE TABLE statement below:
CREATE TABLE Room (Room_Num int AUTO_INCREMENT PRIMARY KEY, Room_Name varchar(255) NOT NULL, Build_Num int NOT NULL,
FOREIGN KEY (Build_Num)
REFERENCES Building (Build_Num)
ON DELETE CASCADE) ENGINE = InnoDB;
Example #3 – Entering some inputs in the tables created above
INSERT INTO Building(Build_Name, Build_Address) VALUES('Sahara Apartments','Sector62, Noida'), ('South City','Baduan, Bareily');
To view data from Building table:
SELECT * FROM Building;
For Room Table:
INSERT INTO Room(Room_Name, Build_Num) VALUES('PawanVihar','1'), ('Acme Floors','1'),('Mecon Floors','1') ,('Amazon','2'),('Tata Showroom','2');
SELECT * FROM Room;
Example #4 – Deleting Build_Num 2 from Building table
DELETE FROM Building WHERE Build_Num=2;
SELECT * FROM Building;
Example #5 – Querying Rows from Room Table
SELECT * FROM Room;
Initially, 3 rooms associated with building number 1 and 2 rooms linked to building number 2. So, now by deleting the Build_Num 2 in the parent table, we can see that the rooms referenced with foreign key Build_Num in Room table are also auto-deleted simultaneously.
Example #6 – Finding Table affected by ON DELETE CASCADE in MySQL
If we want to know the CASCADE affected table by MYSQL ON DELETE CASCADE for the foreign key to old referential action when we delete data from the related table, then we need to apply query in the information_schema database in the phpMyAdmin or database panel with syntax as follows:
SELECT Table_Name FROM referential_constraints
constraint_schema = 'achu'
AND referenced_Table_Name = 'Building'
AND delete_rule = 'CASCADE'
Using this type of MySQL delete statement helps to automatically remove the associated table data whenever we delete the data in the paternal table to save our time, manage the table records easily, fetch updated rows and organize the database size as well as improves usage of the referential action for a foreign key.
This is a guide to MySQL ON DELETE CASCADE. Here we discuss How ON DELETE CASCADE works in MySQL along with programming examples. You may also have a look at the following articles to learn more –