Triggers are special stored programs that are automatically executed when specific events occur in a database table. They are primarily used to maintain data integrity, enforce business rules, audit changes, and automate processes.
DELIMITER //
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE} ON table_name
FOR EACH ROW
BEGIN
-- trigger body statements
END //
DELIMITER ;
MySQL provides special references for accessing row data:
NEW
: Refers to the new row being inserted or the updated values in an UPDATEOLD
: Refers to the existing row being updated or deletedBEFORE triggers execute before the actual DML operation occurs. They're useful for: