BEFORE and AFTER Triggers in SQL – Explained with Syntax & Examples
What Are BEFORE and AFTER Triggers?
Triggers in SQL automatically execute custom logic before or after specific data manipulation events (INSERT, UPDATE, or DELETE) on a table.
There are two key types:
- BEFORE Trigger: Executes before the database action takes place
- AFTER Trigger: Executes after the database action completes successfully
Understanding the difference is crucial for enforcing business rules, validating data, and auditing changes.
Difference Between BEFORE and AFTER Triggers
Feature | BEFORE Trigger | AFTER Trigger |
---|---|---|
Execution Timing | Runs before the actual operation | Runs after the operation is committed |
Usage | Validate or modify incoming data | Log changes, update related tables |
Access to Data | Uses NEW and OLD values | Uses NEW and OLD values |
Can Modify Data | Yes (you can change NEW values) | No (data has already been written) |
Rollback Control | Can prevent invalid data from being inserted | Cannot stop the operation from completing |
Syntax
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- SQL logic
END;
Example 1: BEFORE INSERT Trigger
Prevent inserting users with empty emails:
CREATE TRIGGER before_insert_user
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
IF NEW.email IS NULL OR NEW.email = '' THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Email cannot be empty';
END IF;
END;
Executed before the insert. If the email is blank, the insertion fails.
Example 2: AFTER INSERT Trigger
Log every new customer record into an audit table:
CREATE TRIGGER after_insert_customer
AFTER INSERT ON customers
FOR EACH ROW
BEGIN
INSERT INTO customer_log(customer_id, action, created_at)
VALUES (NEW.id, 'INSERT', NOW());
END;
Executed after the new customer is successfully added.
Example 3: BEFORE UPDATE Trigger
Enforce salary constraint before update:
CREATE TRIGGER before_salary_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
IF NEW.salary < 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Salary cannot be negative';
END IF;
END;
Example 4: AFTER DELETE Trigger
Record deletions to an archive table:
CREATE TRIGGER after_employee_delete
AFTER DELETE ON employees
FOR EACH ROW
BEGIN
INSERT INTO deleted_employees(id, name, deleted_at)
VALUES (OLD.id, OLD.name, NOW());
END;
When to Use BEFORE vs AFTER
Scenario | Trigger Type |
---|---|
Validate or sanitize input data | BEFORE |
Prevent invalid transactions | BEFORE |
Log changes to an audit table | AFTER |
Update related or summary tables | AFTER |