1. Syntax for Creating a Trigger
CREATE TRIGGER trigger_name
BEFORE | AFTER INSERT | UPDATE | DELETE
ON table_name
FOR EACH ROW
BEGIN
-- SQL statements
END;
BEFORE | AFTER
: Defines when the trigger executes.INSERT | UPDATE | DELETE
: Specifies the event that activates the trigger.Let’s assume we have a students
table and want to automatically record updates in a student_logs
table whenever a student’s data is modified.
CREATE TRIGGER after_student_update
AFTER UPDATE ON students
FOR EACH ROW
BEGIN
INSERT INTO student_logs(student_id, action, timestamp)
VALUES (OLD.id, 'Updated', NOW());
END;
students
table.student_logs
table.MySQL Triggers are a powerful way to automate database actions based on predefined events. They help maintain data consistency, improve security, and reduce the need for manual intervention.