DBMS Lab7
DBMS Lab7
PROBLEM STATEMENT
TRIGGERS IN MySQL
In MySQL, a trigger is a set of SQL statements that is invoked automatically when a change is made to the
data on the associated table. A trigger can be defined to be invoked either before or after the data is
changed by INSERT, UPDATE or DELETE statement. BEFORE INSERT – activated before data is inserted into
the table.
When you use a statement that does not use INSERT, DELETE or UPDATE statement to change data in a
table, the triggers associated with the table are not invoked. For example, the TRUNCATE statement
removes all data of a table but does not invoke the trigger associated with that table.
There are some statements that use the INSERT statement behind the scenes such as REPLACE
statement or LOAD DATA statement. If you use these statements, the corresponding triggers associated
with the table are invoked.
You must use a unique name for each trigger associated with a table. However, you can have the same
trigger name defined for different tables though it is not a good practice.
In order to create a new trigger, you use the CREATE TRIGGER statement. The following illustrates the
syntax of the CREATE TRIGGER statement:
You put the trigger name after the CREATE TRIGGER statement. The trigger name should follow
the naming convention [trigger time]_[table name]_[trigger event], for
example before_employees_update.
Trigger activation time can be BEFORE or AFTER. You must specify the activation time when you
define a trigger. You use the BEFORE keyword if you want to process action prior to the change is
made on the table and AFTER if you need to process action after the change is made.
The trigger event can be INSERT, UPDATE or DELETE. This event causes the trigger to be invoked.
A trigger only can be invoked by one event. To define a trigger that is invoked by multiple events,
you have to define multiple triggers, one for each event.
A trigger must be associated with a specific table. Without a table trigger would not exist
therefore you have to specify the table name after the ON keyword.
You place the SQL statements between BEGIN and END block. This is where you define the logic
for the trigger.
PRACTICE PROBLEM
Now, create a new table named customer_audit to keep the changes of the customer table.
SOLUTION
Now, create a BEFORE UPDATE trigger that is invoked before a change is made to the customer table.
DELIMITER $$
CREATE TRIGGER before_customer_update
BEFORE UPDATE ON Customer
FOR EACH ROW
BEGIN
INSERT INTO customer_audit
SET action = 'update',
customerId = OLD.Cid,
creditlimit = OLD.CreditLimit,
changedat = NOW();
END$$
DELIMITER ;
To view all triggers in the current database, you use SHOW TRIGGERS statement as follows:
SHOW TRIGGERS;
After that, update the Customer table to check whether the trigger is invoked.
Finally, to check if the trigger was invoked by the UPDATE statement, you can query the customer_aui
t table using the following query: