This tutorial explains how to create a BEFORE UPDATE Trigger in MySQL with syntax and examples.
A BEFORE UPDATE Trigger means that MySQL will fire this trigger before the UPDATE operation is executed.
The syntax to create a BEFORE UPDATE Trigger in MySQL is:
CREATE TRIGGER <strong>trigger_name</strong>
BEFORE UPDATE
ON <strong>table_name</strong> FOR EACH ROW
BEGIN
-- variable declarations
-- trigger code
END;
The name of the trigger to create.
It indicates that the trigger will fire before the UPDATE operation is executed.
The name of the table that the trigger is created on.
Let's look at an example of how to create an BEFORE UPDATE trigger using the CREATE TRIGGER statement in MySQL.
If you had a table created as follows:
CREATE TABLE contacts
( contact_id INT(11) NOT NULL AUTO_INCREMENT,
last_name VARCHAR(30) NOT NULL,
first_name VARCHAR(25),
birthday DATE,
created_date DATE,
created_by VARCHAR(30),
CONSTRAINT contacts_pk PRIMARY KEY (contact_id)
);
We could then use the CREATE TRIGGER statement to create an BEFORE UPDATE trigger as follows:
DELIMITER //
CREATE TRIGGER contacts_before_update
BEFORE UPDATE
ON contacts FOR EACH ROW
BEGIN
DECLARE vUser varchar(50);
-- Find username of person performing the INSERT into table
SELECT USER() INTO vUser;
-- Insert record into audit table
INSERT INTO contacts_audit
( contact_id,
updated_date,
updated_by)
VALUES
( NEW.contact_id,
SYSDATE(),
vUser );
END; //
DELIMITER ;