Skip to main content
SQL Fundamentals
CHAPTER 25 Beginner

SQL Triggers | Automate Database Events

Updated: May 16, 2026
15 min read

# CHAPTER 25

Triggers and Database Automation

1. Introduction

In standard SQL, the database is reactive. It sits idle, waiting for the web application (PHP or Node.js) to send an INSERT or UPDATE command. But what if the database could act on its own? What if, the exact millisecond a rogue employee tries to UPDATE a salary, the database automatically intercepts the command, logs the employee's name, and records the exact time? In this chapter, we will master Triggers—the mechanism that transforms a passive database into an active, self-monitoring, automated engine.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the architectural purpose of an SQL Trigger.
  • Understand the event timing (BEFORE vs AFTER).
  • Understand the event types (INSERT, UPDATE, DELETE).
  • Access data states using the NEW and OLD keywords.
  • Build an automated Audit Logging system.

3. What is a Trigger?

A Trigger is a saved block of SQL code that automatically executes (fires) when a specific event occurs on a specific table. You do not CALL a trigger. You cannot force a trigger to run manually. It fires automatically in the background when its conditions are met.

Events that can fire a Trigger:

  • INSERT
  • UPDATE
  • DELETE

Timing of the Trigger:

  • BEFORE: Fires *before* the data is physically saved to the hard drive (Useful for data validation/modification).
  • AFTER: Fires *after* the data is safely written (Useful for auditing or updating other tables).

4. Creating an AFTER Trigger (Audit Logging)

Let's build a security system. Every time someone changes an employee's salary, we want the database to automatically insert a record into a salary_audit table.

We use the magical keywords OLD (the data before the update) and NEW (the data after the update).

sql
12345678910111213141516
DELIMITER //

CREATE TRIGGER AfterSalaryUpdate
-- Firing Rule: After a row is updated in the employees table...
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
    -- Check if the salary column specifically was changed
    IF OLD.salary != NEW.salary THEN
        -- Automatically insert a log! The PHP backend doesn't even know this is happening!
        INSERT INTO salary_audit (employee_id, old_salary, new_salary, changed_at)
        VALUES (NEW.id, OLD.salary, NEW.salary, NOW());
    END IF;
END //

DELIMITER ;

*(Result: If an admin runs UPDATE employees SET salary = 90000 WHERE id = 5;, the trigger silently fires in the background, permanently saving a trail of the action).*

5. Creating a BEFORE Trigger (Data Validation)

What if we want to stop bad data *before* it gets saved? Suppose an application tries to insert a negative price for a product. We can use a BEFORE INSERT trigger to intercept the data, and automatically correct it to $0.00!
sql
123456789101112131415
DELIMITER //

CREATE TRIGGER PreventNegativePrice
-- Firing Rule: Intercept the data BEFORE it saves to the hard drive
BEFORE INSERT ON products
FOR EACH ROW
BEGIN
    -- Check the incoming data payload (NEW)
    IF NEW.price < 0 THEN
        -- Silently overwrite the bad data with a 0!
        SET NEW.price = 0;
    END IF;
END //

DELIMITER ;

6. Mini Project: E-Commerce Inventory Automation

When an order is placed, the inventory must decrease. Instead of relying on the web application to remember to run the UPDATE inventory query, let's make the database do it automatically.
sql
12345678910111213
DELIMITER //

CREATE TRIGGER DeductInventory
AFTER INSERT ON order_items
FOR EACH ROW
BEGIN
    -- Automatically reduce the stock of the specific product purchased
    UPDATE inventory 
    SET stock_quantity = stock_quantity - NEW.quantity
    WHERE product_id = NEW.product_id;
END //

DELIMITER ;

*(Now, inserting an order item mathematically guarantees the inventory is synced. Flawless architecture!)*

7. The Danger of Cascading Triggers

Triggers are powerful, but incredibly dangerous. Imagine Table A has a trigger that updates Table B. Table B has a trigger that updates Table C. Table C has a trigger that updates Table A. If you execute a single INSERT on Table A, you create an infinite loop of triggers firing each other until the database crashes. This is called a Cascading Trigger Nightmare.

8. Common Mistakes

  • Hidden Logic Debugging: Because Triggers run silently in the background, they are notorious for causing "ghost" bugs. A Node.js developer inserts an Order, and the Inventory mysteriously decreases. The developer spends 10 hours checking their JavaScript code, not realizing a Database Trigger is doing it! Always document your triggers clearly.

9. Best Practices

  • Keep Triggers Tiny: A trigger executes *every single time* a row is touched. If your trigger contains a massive, 10-second JOIN query, and you try to UPDATE 1,000 rows, your database will freeze for 10,000 seconds. Triggers must be instantaneous, simple logic.

10. Exercises

  1. 1. What two keywords are used inside an UPDATE trigger to access the data payload before and after the modification?
  1. 2. If you want a trigger to physically intercept and alter incoming data before it is saved to the table, what timing clause must you use?

11. SQL Challenges

Write the DDL to drop an existing trigger. Assume the trigger is named PreventNegativePrice.
sql
1
DROP TRIGGER PreventNegativePrice;

12. MCQ Quiz with Answers

Question 1

What is the defining operational characteristic of a Database Trigger?

Question 2

When writing a Trigger for an UPDATE event, what do the OLD and NEW pseudo-records represent?

13. Interview Questions

  • Q: Explain an architectural scenario where implementing a BEFORE UPDATE trigger is heavily favored over implementing an AFTER UPDATE trigger.
  • Q: A junior developer suggests using Triggers to handle all business logic (e.g., sending welcome emails, calculating taxes, managing inventory) to keep the backend Python code "clean." Argue against this architectural pattern, specifically addressing the concepts of "Hidden Logic" and Trigger Cascading.

14. FAQs

Q: Can a Trigger stop an INSERT entirely? A: Yes! In a BEFORE INSERT trigger, you can write logic that evaluates the incoming data. If the data is malicious, you can execute a SIGNAL SQLSTATE (in MySQL) or RAISE EXCEPTION (in PostgreSQL) to instantly abort the transaction and throw an error to the frontend application.

15. Summary

You have breathed life into the database schema. By mastering BEFORE and AFTER Triggers, utilizing NEW and OLD data states, and architecting silent audit trails, you have transformed the database from a passive storage drive into an active, self-regulating entity that fiercely protects its own data integrity.

16. Next Chapter Recommendation

Our database is perfectly optimized, automated, and architecturally sound. But it is vulnerable to the most devastating attack vector in computer science. In Chapter 26: Database Security and SQL Injection Prevention, we will learn how hackers destroy databases, and exactly how to stop them.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·