Event triggers automatically run SQL before or after INSERT, UPDATE, or DELETE statements on a table.
MySQL triggers are stored programs that fire automatically before or after INSERT, UPDATE, or DELETE events on a table. They help you enforce business rules, maintain audit logs, and keep related data in sync without changing application code.
Use BEFORE triggers when you must validate or transform incoming data before it reaches the table.Examples include setting default dates, normalizing text, or rejecting invalid totals.
AFTER triggers run once the row is safely stored, making them ideal for writing to audit tables, updating aggregates, or sending notifications that depend on committed data.
Create an AFTER INSERT trigger on OrderItems
.Each time a new order item is saved, the trigger subtracts the sold quantity from Products.stock
, keeping inventory accurate.
CREATE TRIGGER oi_ai_update_stock
AFTER INSERT ON OrderItems
FOR EACH ROW
UPDATE Products
SET stock = stock - NEW.quantity
WHERE id = NEW.product_id;
The complete CREATE TRIGGER
syntax lets you choose timing, event, order, and body. See the full syntax section below.
Keep trigger logic short, use explicit column lists, handle errors gracefully, and document side effects.Test thoroughly because triggers run invisibly to calling code.
Use DROP TRIGGER [schema.]trigger_name;
to delete. To change logic, drop and recreate; MySQL does not support ALTER TRIGGER
.
Do not perform long-running queries inside a trigger—this slows every DML statement.Also avoid referencing tables that may cause recursive trigger calls unless you disable the second trigger.
Timing: BEFORE | AFTER
Event: INSERT | UPDATE | DELETE
Scope: FOR EACH ROW
Order: FOLLOWS | PRECEDES other_trigger
1. Decide timing and event.
2. Write the SQL body.
3. Grant TRIGGER
privilege.
4. Execute CREATE TRIGGER
statement.
5. Test with sample data.
Consult the MySQL Reference Manual, section "Triggers", for additional restrictions, such as disallowed statements and concurrency considerations.
.
Yes. Use the FOLLOWS or PRECEDES clause to control execution order.
Yes. LOAD DATA and INSERT ... SELECT will execute associated triggers for each affected row.
MySQL lacks DISABLE TRIGGER. Instead, drop the trigger and recreate it later or use session variables inside the trigger to conditionally exit.