Can you give an example of cascading actions?

091

Certainly! Cascading actions in foreign key constraints allow you to automatically update or delete related records in a child table when a record in the parent table is updated or deleted. Here’s an example:

Scenario

Consider two tables: Customers and Orders. Each order is linked to a customer through a foreign key.

Customers Table:

CustomerID Name
1 Alice
2 Bob

Orders Table:

OrderID CustomerID Product
101 1 Laptop
102 1 Mouse
103 2 Keyboard

Cascading Delete Example

If you set up a foreign key constraint on the Orders table that references the Customers table with a cascading delete, it would look like this:

ALTER TABLE Orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
ON DELETE CASCADE;

Action

Now, if you delete a customer from the Customers table:

DELETE FROM Customers WHERE CustomerID = 1;

Result

The database will automatically delete all orders associated with CustomerID 1 from the Orders table. The resulting Orders table would look like this:

OrderID CustomerID Product
103 2 Keyboard

In this case, both orders for Alice (CustomerID 1) are removed automatically due to the cascading delete action. This helps maintain referential integrity without needing to manually delete related records.

0 Comments

no data
Be the first to share your comment!