Answer: Cascading Delete
Find a detailed explanation about using referential integrity constraints.
We'll cover the following...
We'll cover the following...
Solution
The solution is given below:
MySQL
-- The query to enforce referential integrity constraintsSELECT * FROM Skills;ALTER TABLE SkillsADD CONSTRAINT FK_EmpIDFOREIGN KEY (EmpID) REFERENCES Employees(EmpID)ON DELETE CASCADE;DELETE FROM EmployeesWHERE EmpID = 3;SELECT * FROM Skills;
Code explanation
The explanation of the solution code is given below:
- Line 2: This retrieves all the values from the - Skillstable.
- Lines 4–7: The - ALTER TABLEstatement alters the- Skillstable to add a- FOREIGN KEYconstraint named- FK_EmpID. It links- EmpIDin- Skillsto- EmpIDin- Employees, with- ON DELETE CASCADEto remove associated skills if an employee is deleted.
- Lines 9–10: This deletes the employee with - EmpID = 3from the- Employeestable.
- Line 12: This retrieves all the values from the - Skillstable again, reflecting the changes after the employee deletion.
Recalling relevant concepts
We have ...