๐Ÿ”” MySQL Triggers โ€“ Automate Table Logic with BEFORE/AFTER INSERT, UPDATE, DELETE


๐Ÿงฒ Introduction โ€“ Why Use MySQL Triggers?

MySQL Triggers are database-level scripts that automatically run in response to INSERT, UPDATE, or DELETE actions on a table. They help you:

  • โœ… Enforce data rules
  • ๐Ÿ›ก๏ธ Maintain audit trails
  • ๐Ÿ”„ Synchronize tables
  • ๐Ÿ“Š Automate calculations

Triggers eliminate the need for repetitive code in your application logic and ensure consistent behavior directly at the database layer.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to create BEFORE and AFTER triggers
  • Trigger syntax and use cases for INSERT, UPDATE, and DELETE
  • Examples and best practices
  • How to manage and drop triggers

๐Ÿ”„ 1. Trigger Types in MySQL

Trigger TimingTrigger EventPurpose
BEFOREINSERTValidate or transform data before insert
AFTERINSERTAudit or log inserted data
BEFOREUPDATERestrict or pre-process new values
AFTERUPDATERecord changes in audit/history table
BEFOREDELETECapture data before deletion
AFTERDELETEArchive deleted rows

โœ… You can have one trigger per event per timing on a table.


๐Ÿงฑ 2. Syntax โ€“ CREATE TRIGGER

CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name FOR EACH ROW
BEGIN
  -- SQL logic here
END;

Use OLD.column_name to refer to existing data, and NEW.column_name for new values during insert/update.


๐Ÿ”ง 3. BEFORE INSERT Trigger Example

CREATE TRIGGER before_insert_user
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
  SET NEW.created_at = NOW();
END;

Explanation:
Automatically sets created_at before inserting a new user.


๐Ÿงพ 4. AFTER INSERT Trigger โ€“ Logging Example

CREATE TRIGGER after_insert_order
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
  INSERT INTO order_log(order_id, action, logged_at)
  VALUES (NEW.id, 'created', NOW());
END;

โœ… Used for tracking inserts into a separate audit table.


๐Ÿ”„ 5. BEFORE UPDATE Trigger โ€“ Validate or Normalize

CREATE TRIGGER before_update_product
BEFORE UPDATE ON products
FOR EACH ROW
BEGIN
  IF NEW.price < 0 THEN
    SET NEW.price = 0;
  END IF;
END;

โœ… Ensures price is never negative before saving changes.


๐Ÿ“ 6. AFTER UPDATE Trigger โ€“ Change Log

CREATE TRIGGER after_update_email
AFTER UPDATE ON users
FOR EACH ROW
BEGIN
  IF OLD.email != NEW.email THEN
    INSERT INTO email_changes(user_id, old_email, new_email, changed_at)
    VALUES (OLD.id, OLD.email, NEW.email, NOW());
  END IF;
END;

โœ… Tracks email updates without relying on application code.


โŒ 7. BEFORE DELETE Trigger โ€“ Backup Row

CREATE TRIGGER before_delete_customer
BEFORE DELETE ON customers
FOR EACH ROW
BEGIN
  INSERT INTO customer_backup(id, name, email, deleted_at)
  VALUES (OLD.id, OLD.name, OLD.email, NOW());
END;

โœ… Saves a copy of the row before it’s deleted from the main table.


๐Ÿ”ฅ 8. AFTER DELETE Trigger โ€“ Archive Audit

CREATE TRIGGER after_delete_order
AFTER DELETE ON orders
FOR EACH ROW
BEGIN
  INSERT INTO order_archive(order_id, removed_at)
  VALUES (OLD.id, NOW());
END;

โœ… Logs that a row was deleted and when.


๐Ÿ“‹ Trigger Management

๐Ÿ” View Triggers

SHOW TRIGGERS;

โŒ Drop Trigger

DROP TRIGGER IF EXISTS trigger_name;

๐Ÿง  Best Practices

โœ… Tip๐Ÿ’ก Why It Matters
Keep triggers small and fastAvoid performance bottlenecks
Use only for consistent, DB-level logicPrevent logic duplication
Avoid calling external services inside triggersCan slow down or block transactions
Test trigger behavior with different scenariosEnsure correctness and avoid unintended loops
Donโ€™t use triggers to enforce complex business rulesBetter in app layer or procedures

๐Ÿš€ Real-World Use Cases

Use CaseTrigger TypeDescription
Audit data updatesAFTER UPDATESave old and new values in audit table
Log order creationAFTER INSERTWrite to order_log when a new order is made
Archive deleted usersBEFORE DELETECopy user data to archive before deletion
Sanitize input on insertBEFORE INSERTFormat phone numbers or emails
Prevent invalid updatesBEFORE UPDATEBlock changes if new value violates rule

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

MySQL triggers let you automate database logic based on table actions like inserts, updates, or deletes. They improve data integrity, reduce duplication, and allow for real-time reactions to changes in your database.

๐Ÿ” Key Takeaways

  • Use BEFORE triggers to validate or sanitize input
  • Use AFTER triggers to log, audit, or notify
  • Triggers are per table and per event
  • Use NEW and OLD to reference row values
  • Keep trigger logic fast and simple

โš™๏ธ Real-World Relevance

Triggers are widely used in audit logging, change tracking, archiving, data consistency enforcement, and cross-table synchronization in ERP, CRM, finance, and analytics platforms.


โ“ FAQ โ€“ MySQL Triggers


โ“ Can I have multiple triggers for the same event?

โŒ No. MySQL supports only one trigger per timing/event combination per table.


โ“ Whatโ€™s the difference between NEW and OLD?

  • NEW: Refers to the incoming values (INSERT, UPDATE)
  • OLD: Refers to the existing values (UPDATE, DELETE)

โ“ Are triggers transactional?

โœ… Yes. If the query fails, the trigger’s actions are rolled back automatically.


โ“ Can I update the same table inside a trigger?

โš ๏ธ No. MySQL prevents recursive updates (e.g., UPDATE triggering itself).


โ“ How do I list all triggers?

SHOW TRIGGERS;

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ”” MySQL Triggers (BEFORE/AFTER INSERT, UPDATE, DELETE)

Or Copy Link

CONTENTS
Scroll to Top