bg_image
header

Database triggers

🔧 What are Database Triggers?

Database triggers are special automated procedures in a database that are automatically executed when certain events occur on a table or view.


🧠 Example:

Imagine you have a table called Orders, and you want to automatically log every time an order is deleted.
You can create a DELETE trigger on the Orders table that inserts a message into a Log table whenever a row is deleted.


🔄 Types of Triggers:

Type Description
BEFORE Executes before the triggering action
AFTER Executes after the triggering action
INSTEAD OF (for views) replaces the triggering action
CREATE TRIGGER log_delete
AFTER DELETE ON Orders
FOR EACH ROW
BEGIN
  INSERT INTO Log (action, timestamp)
  VALUES ('Order deleted', NOW());
END;

✅ Common Uses of Triggers:

  • Data validation

  • Audit logging

  • Enforcing business rules

  • Extending referential integrity


⚠️ Disadvantages:

  • Can be hard to debug

  • Might trigger other actions unexpectedly

  • Can impact performance if overly complex