A trigger in MySQL is a stored set of SQL statements executed automatically in response to events on a table (INSERT, UPDATE, DELETE). Triggers help enforce data integrity, perform auditing, or modify data automatically without changing application code.
BEFORE or AFTER an event.INSERT, UPDATE, DELETE.NEW (after), OLD (before).
-- Trigger skeleton: timing, event, table and per-row block
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- trigger logic goes here
END;
-- Use DELIMITER when creating multi-statement triggers in many clients
DELIMITER $$
CREATE TRIGGER before_employee_insert
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
-- Set created_at field to current timestamp before inserting
SET NEW.created_at = NOW();
END$$
DELIMITER ;
-- Test the trigger by inserting a new employee
INSERT INTO employees (name, position) VALUES ('John Doe', 'Manager');
-- Example: log deleted rows into audit table
DELIMITER $$
CREATE TRIGGER after_employee_delete
AFTER DELETE ON employees
FOR EACH ROW
BEGIN
-- Insert deleted row details into employees_backup table
INSERT INTO employees_backup (employee_id, name, position, deleted_at)
VALUES (OLD.id, OLD.name, OLD.position, NOW());
END$$
DELIMITER ;
Simulating a BEFORE INSERT trigger. The trigger will force the Name to Uppercase and add a Timestamp.
CREATE TRIGGER before_insert_demo BEFORE INSERT ON employees FOR EACH ROW
BEGIN
SET NEW.name = UPPER(NEW.name); -- Force Uppercase
SET NEW.joined_at = NOW(); -- Add missing Timestamp
END;
| ID | Name | Position | Joined_At (Triggered) |
|---|
The before_employee_insert trigger runs automatically before each row is inserted into employees. It sets the created_at column to the current timestamp, ensuring the value is populated even when the INSERT omits it.
The after_employee_delete trigger records deleted rows into a backup table for audit/history.
before_insert_employees).AFTER INSERT trigger on an orders table to deduct stock from products.BEFORE UPDATE trigger to normalize text fields (e.g., trim and lowercase).