Reading history

SQL Triggers: BEFORE and AFTER with Examples

5 min read 0 views

Learn SQL triggers with working examples: audit logs with OLD and NEW, rejecting changes with RAISE, BEFORE vs AFTER, and trigger syntax in MySQL, PostgreSQL and SQL Server.

A trigger is SQL code that the database runs automatically when you insert, update or delete a row. You can use one to keep an audit log of every balance change, block an update that breaks a business rule, or keep a summary table up to date. The code lives inside the database, so it runs whichever application or user made the change. This lesson builds three working triggers in SQLite and shows how other databases differ.

In this lesson you will learn

  • The parts of CREATE TRIGGER: timing, event, table and body
  • BEFORE vs AFTER triggers
  • The OLD and NEW row values
  • Rejecting a change with RAISE
  • When triggers help and when they cause trouble

You should know INSERT, UPDATE and DELETE and the CASE expression.

An Audit Log Trigger

CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER);
CREATE TABLE audit_log (
    account_id  INTEGER,
    old_balance INTEGER,
    new_balance INTEGER,
    note        TEXT
);
INSERT INTO accounts VALUES (1, 'Karim', 5000), (2, 'Rina', 1200);

-- Record every balance change automatically
CREATE TRIGGER log_balance_change
AFTER UPDATE OF balance ON accounts
FOR EACH ROW
BEGIN
    INSERT INTO audit_log VALUES (OLD.id, OLD.balance, NEW.balance,
        CASE WHEN NEW.balance > OLD.balance THEN 'deposit' ELSE 'withdrawal' END);
END;

UPDATE accounts SET balance = balance - 700 WHERE id = 1;
UPDATE accounts SET balance = balance + 300 WHERE id = 2;
UPDATE accounts SET owner = 'Rina Akter' WHERE id = 2;

SELECT * FROM audit_log;

Output

+------------+-------------+-------------+------------+
| account_id | old_balance | new_balance | note       |
+------------+-------------+-------------+------------+
| 1          | 5000        | 4300        | withdrawal |
| 2          | 1200        | 1500        | deposit    |
+------------+-------------+-------------+------------+
(2 rows)
  • AFTER UPDATE OF balance ON accounts says when the trigger fires: after an update that changes the balance column of accounts.
  • FOR EACH ROW runs the body once for every row changed. An update of 100 rows writes 100 log entries.
  • Inside the body, OLD is the row before the change and NEW is the row after it. An INSERT trigger has only NEW, and a DELETE trigger only OLD.
  • Two balance updates produced two log rows. The third update changed only owner, so the trigger did not fire.
  • Nobody had to remember to write to audit_log: the database did it.

Enforcing Rules and Updating Summaries

CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER);
INSERT INTO accounts VALUES (1, 'Karim', 5000), (2, 'Rina', 1200);

-- Reject any update that would make a balance negative
CREATE TRIGGER no_overdraft
BEFORE UPDATE OF balance ON accounts
FOR EACH ROW
WHEN NEW.balance < 0
BEGIN
    SELECT RAISE(ABORT, 'insufficient funds');
END;

-- fails: Rina only has 1200
UPDATE accounts SET balance = balance - 2000 WHERE id = 2;

UPDATE accounts SET balance = balance - 1000 WHERE id = 2;

-- Keep a running count of accounts in a summary table
CREATE TABLE bank_stats (accounts INTEGER);
INSERT INTO bank_stats VALUES (2);
CREATE TRIGGER count_new_account AFTER INSERT ON accounts
BEGIN
    UPDATE bank_stats SET accounts = accounts + 1;
END;
INSERT INTO accounts VALUES (3, 'Joya', 800);

SELECT a.*, s.accounts AS total_accounts FROM accounts a, bank_stats s ORDER BY a.id;

-- Triggers are stored in the schema
SELECT name, tbl_name FROM sqlite_master WHERE type = 'trigger' ORDER BY name;

Output

Error: insufficient funds

+----+-------+---------+----------------+
| id | owner | balance | total_accounts |
+----+-------+---------+----------------+
| 1  | Karim | 5000    | 3              |
| 2  | Rina  | 200     | 3              |
| 3  | Joya  | 800     | 3              |
+----+-------+---------+----------------+
(3 rows)

+-------------------+----------+
| name              | tbl_name |
+-------------------+----------+
| count_new_account | accounts |
| no_overdraft      | accounts |
+-------------------+----------+
(2 rows)
  • A BEFORE trigger runs before the row is changed, so it can stop the change. The WHEN NEW.balance < 0 condition limits it to updates that would overdraw the account.
  • RAISE(ABORT, 'message') cancels the statement with an error. Withdrawing 2000 from Rina failed; withdrawing 1000 succeeded and left 200.
  • The AFTER INSERT trigger keeps bank_stats in step with the number of accounts, so reports do not need to count rows every time.
  • Triggers are part of the schema; in SQLite they are listed in sqlite_master. Remove one with DROP TRIGGER name;.
  • A simple rule like “balance must not be negative” could also be a CHECK (balance >= 0) constraint. Prefer constraints when they can do the job, and use triggers for rules that need other tables or custom messages.

Triggers in Other Databases

DatabaseNotes
SQLiteBody written directly between BEGIN and END; RAISE() to reject
MySQLSimilar syntax; reject with SIGNAL SQLSTATE '45000'; change the delimiter in the command-line client
PostgreSQLWrite a trigger function in PL/pgSQL, then CREATE TRIGGER … EXECUTE FUNCTION fn()
SQL ServerStatement-level only; use the inserted and deleted tables instead of OLD/NEW

Common Mistakes

  1. Hiding important logic in triggers, so developers are surprised by side effects they cannot see in the code.
  2. Slow triggers on busy tables. A row-level trigger runs for every row, so heavy work multiplies quickly.
  3. Triggers that fire other triggers, creating chains that are hard to debug.
  4. Using a trigger where a constraint or foreign key would do.

Practice Exercises

Exercise 1. Write a trigger that records every deleted account in a deleted_accounts(id, owner, balance) table.

Show answer
CREATE TRIGGER keep_deleted_account
AFTER DELETE ON accounts
FOR EACH ROW
BEGIN
    INSERT INTO deleted_accounts VALUES (OLD.id, OLD.owner, OLD.balance);
END;

Exercise 2. Write a trigger that stores every new account owner’s name in capital letters.

Show answer
CREATE TRIGGER upper_owner
AFTER INSERT ON accounts
FOR EACH ROW
BEGIN
    UPDATE accounts SET owner = UPPER(NEW.owner) WHERE id = NEW.id;
END;

SQLite cannot change NEW directly, so the trigger updates the row after it is inserted. In MySQL and PostgreSQL, a BEFORE INSERT trigger can set NEW.owner instead.

Frequently Asked Questions

Do triggers run inside the same transaction?

Yes. If the trigger fails, the database also rolls back the statement that fired it, so it never leaves the data half-changed.

What is an INSTEAD OF trigger?

A trigger on a view that runs in place of the insert, update or delete, letting you decide how changes to the view are applied to the underlying tables. See SQL views.

Summary

  • A trigger runs automatically on INSERT, UPDATE or DELETE.
  • BEFORE triggers can check and reject; AFTER triggers react.
  • OLD and NEW hold the row before and after the change.
  • Use triggers for audits and cross-table rules, and keep them small.

Next: SQL JSON Functions.

Lessons are also marked complete when you click Next.

Leave a Reply

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