How to delete using INNER JOIN
Overview
In SQL, we use INNER JOIN to join the data of two tables. In some cases, we delete data using an inner join.
To delete the data by using the inner join, the syntax is given below:
Syntax
DELETE firstTable
FROM firstTable INNER JOIN secondTable ON
firstTable.attributeName = secondTable.attributeName
WHERE condition
Suppose we have a table Persons with the following data:
SELECT * FROM Person;
Next, we will create another table named ProjectManager with the following data:
SELECT * FROM ProjectManager;
We use INNER JOIN to delete the ProjectManager above age and fetch the date_of_birth of the Person to calculate the age at the time of deletion. We will run the following query:
DELETE ProjectManagerFROM ProjectManager INNER JOIN Person ONProjectManager.p_id = Person.person_idWHERE TIMESTAMPDIFF(YEAR, Person.date_of_birth, '2021-01-23') >= 50;
Explanation
-
Line 1: Delete data from
ProjectManager. -
Line 2–4: We join the
ProjectManagerand thePersonstable based on their relationperson_id. Next, we delete the data of theProjectManagerwhose age is above .