Triggers Exercise



One of the requirements of a database is that once a query is committed it cannot be undone.

In this exercise you will implement an undo function using a trigger and a stored procedure that allows an UNDO operation on the CUSTOMER table.


Trigger:

A DELETE trigger saves deleted data in a virtual table called OLD.

The following example shows the code for a trigger that saves the data from the NorthWind categories table to a table called categoriesBackup whenever an item is deleted from the categories table.

DELIMITER $$
CREATE TRIGGER tr_del_saveCategory BEFORE DELETE ON categories
  FOR EACH ROW
    BEGIN
      INSERT INTO categoriesBackup(CategoryID, CategoryName, Description, Picture)
      VALUES(OLD.CategoryID, OLD.CategoryName, OLD.Description, OLD.Picture);
    END$$
DELIMITER ;

Before this trigger can be run, the categoriesBackup table must be created. See the table cloning explanation for an example.


Exercise:

Write a trigger named tr_del_saveCustomerInfo to save the deleted data from the NorthWind customers table into a backup table called backupCustomers.


Testing:

In order to test this trigger, a customer must be deleted from the customers table and backed up to the backupCustomers table.

Try it with a query like

DELETE FROM customers WHERE CustomerID = "WANDK";

Hence, you need to find a customer (or customers) with no outstanding orders.

SELECT customers.CustomerID FROM customers LEFT JOIN orders ON customers.CustomerID = orders.CustomerID;

One of the customers with no outstanding orders is Hungry Owl All-Night Grocers. To delete Hungry Owl All-Night Grocers, use the query:

DELETE FROM customers WHERE CustomerID = "HUNGO";

Now open the customer table and verify that Hungry Owl All-Night Grocers is no longer in the table (you may need to change the "Number of rows" option to All to verify its absence).

Next, open the backupCustomers table to verify that Hungry Owl All-Night Grocers is now in the table.


For a trigger tutorial with a great example, visit this link.


Solution