Creating Trigger in MySql

Posted on July 25, 2019
trigger
mysql
914

MySQL trigger syntax : 

In order to create a new trigger, you use the CREATE TRIGGER statement.  

Syntax of the CREATE TRIGGER statement:

CREATE TRIGGER trigger_name trigger_time trigger_event
 ON table_name
 FOR EACH ROW
 BEGIN
 ...
 END;
  • 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 INSERTUPDATE 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.

Mysql Trigger Example :

Let's create Trigger on the Employee table.

Step 1 : First, create a new table named employees_audit to keep the changes of the employee table. The following statement creates the employee_audit table.


CREATE TABLE employees_audit (
    id INT AUTO_INCREMENT PRIMARY KEY,
    employeeNumber INT NOT NULL,
    lastname VARCHAR(50) NOT NULL,
    changedat DATETIME DEFAULT NULL,
    action VARCHAR(50) DEFAULT NULL
);

Step 2 : Next, create a BEFORE UPDATE trigger that is invoked before a change is made to the employees table.

DELIMITER $$
CREATE TRIGGER before_employee_update 
    BEFORE UPDATE ON employees
    FOR EACH ROW 
BEGIN
    INSERT INTO employees_audit
    SET action = 'update',
     employeeNumber = OLD.employeeNumber,
        lastname = OLD.lastname,
        changedat = NOW(); 
END$$
DELIMITER ;

Inside the body of the trigger, we used the OLD keyword to access employeeNumber and lastname column of the row affected by the trigger.

Now trigger is created and you can see the triggers in the current database using the following statement.

SHOW TRIGGERS;

 




0 comments

Please log in to leave a comment.