Answer: Cascading Referential Actions
Explore how cascading referential actions ensure database consistency in MySQL. Learn to implement ON UPDATE CASCADE and ON DELETE CASCADE rules, test their behavior through SQL queries, and understand alternate methods like triggers or views to maintain data integrity when parent records change or are deleted.
We'll cover the following...
Solution
The solution is given below:
Explanation
The explanation of the solution code is given below:
Lines 1–14: Create the
CustomerAddressestable with columns for address details and a foreign key columnCustomerID.Lines 9–13: Define the foreign key constraint
fk_customeraddresses_customerreferencingCustomers(CustomerID)withON UPDATE CASCADEandON DELETE CASCADE, ensuring related rows follow parent changes.
Lines 20–21: Insert a customer record to generate a new
CustomerIDfor testing cascade behavior.Line 24: Store the inserted customer’s
CustomerIDin the session variable@old_idfor reuse.Lines 27–28: Insert a matching address into
CustomerAddressesusing the captured ID.Lines 31–33: Update the parent
CustomerIDto simulate a migration scenario. Because ofON UPDATE CASCADE, all dependent rows update ...