Triggers

Updated · 9 min read
hardPostgreSQL 18sqltriggersaudit-logplpgsqlbefore-triggerafter-triggerinterview

A trigger in SQL is code the database runs automatically when a row is inserted, updated or deleted in a table. Nobody calls it: the change itself sets it off. It is used for work that must happen on every change, no matter which program made it, such as keeping an audit log of fee changes or cleaning up values before they're saved. In this lesson, we will build an audit log with an AFTER trigger, fix values with a BEFORE trigger, read the OLD and NEW rows, and look honestly at the pitfalls that make experienced developers use triggers sparingly.

In One Minute

  • A trigger has two parts: a trigger function (RETURNS trigger) and a CREATE TRIGGER that attaches it to a table.
  • BEFORE triggers run before the row is written and can change or reject it.
  • AFTER triggers run after the row is written; ideal for audit logs.
  • OLD is the row before the change, NEW the row after; TG_OP says which operation it was.
  • Triggers are hidden work: powerful, but easy to forget when debugging.

Syntax

SQL
CREATE FUNCTION function_name() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  -- use OLD, NEW, TG_OP
  RETURN NEW;   -- or OLD, or NULL
END;
$$;
 
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE [OF column] | DELETE} [OR ...]
ON table_name
FOR EACH {ROW | STATEMENT}
EXECUTE FUNCTION function_name();
PartMeans
BEFORE / AFTERRun before or after the row is written
UPDATE OF fee_usdFire only when that column appears in the UPDATE's SET list
FOR EACH ROWRun once per changed row (FOR EACH STATEMENT: once per statement)
OLD, NEWThe row before and after the change (OLD is null for INSERT, NEW for DELETE)
TG_OP'INSERT', 'UPDATE' or 'DELETE'

An Audit Log with an AFTER Trigger

An audit log records every change: what changed, from what, to what, and when. The trigger fills it, so no program can forget:

SQL▶ Try it
CREATE TABLE fee_audit (
  audit_id   INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  course_id  INTEGER NOT NULL,
  old_fee    NUMERIC(8,2),
  new_fee    NUMERIC(8,2),
  changed_at TIMESTAMP NOT NULL DEFAULT TIMESTAMP '2026-01-05 09:00'
);
 
CREATE FUNCTION log_fee_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO fee_audit (course_id, old_fee, new_fee)
  VALUES (OLD.course_id, OLD.fee_usd, NEW.fee_usd);
  RETURN NULL;
END;
$$;
 
CREATE TRIGGER courses_fee_audit
AFTER UPDATE OF fee_usd ON courses
FOR EACH ROW
EXECUTE FUNCTION log_fee_change();
 
UPDATE courses SET fee_usd = fee_usd * 1.10 WHERE technology = 'Java';
 
SELECT a.audit_id, c.title, a.old_fee, a.new_fee
FROM fee_audit AS a
JOIN courses AS c ON c.course_id = a.course_id
ORDER BY a.audit_id;
Output
CREATE TABLE
 
CREATE FUNCTION
 
CREATE TRIGGER
 
UPDATE 3
 
 audit_id |      title       | old_fee | new_fee
----------+------------------+---------+---------
        1 | Java Basics      |  450.00 |  495.00
        2 | Java OOP         |  500.00 |  550.00
        3 | Java Collections |  550.00 |  605.00
(3 rows)

Explanation: The UPDATE raised three Java fees by 10%, and the trigger ran once for each row, logging the old and new fee. The UPDATE never mentioned fee_audit; the trigger did that work. An AFTER row trigger's return value is ignored, so it returns NULL. (A real log would default changed_at to now(); a fixed time keeps this lesson's output the same every run.)

One UPDATE of three Java fees; the trigger writes one audit row per changed course

Fixing Rows with a BEFORE Trigger

A BEFORE row trigger can change NEW before it's saved. Whatever it returns is what gets written. This one tidies payment methods typed with odd capitals or spaces:

SQL▶ Try it
CREATE FUNCTION tidy_method() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  NEW.method := lower(trim(NEW.method));
  RETURN NEW;
END;
$$;
 
CREATE TRIGGER payments_tidy_method
BEFORE INSERT OR UPDATE OF method ON payments
FOR EACH ROW
EXECUTE FUNCTION tidy_method();
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 4, 150.00, '2026-01-05', '2026-01-05', '  Card ');
 
SELECT payment_id, amount_usd, method FROM payments WHERE student_id = 102;
Output
CREATE FUNCTION
 
CREATE TRIGGER
 
INSERT 0 1
 
 payment_id | amount_usd | method
------------+------------+--------
          8 |     150.00 | card
(1 row)

Explanation: ' Card ' would fail the CHECK (method IN ('card', 'check', 'cash')) constraint. The BEFORE trigger runs first and turns it into 'card', so the check passes. Returning NEW says "save this row".

BEFORE triggers can change or skip the row; then constraints are checked and the row is written; then AFTER triggers run

Order of Events

StepWhat happens
1BEFORE row triggers run, in alphabetical order by trigger name; each can change NEW
2Constraints (NOT NULL, CHECK, UNIQUE, foreign keys) are checked
3The row is written
4AFTER row triggers run, in alphabetical order

Everything happens inside the statement's transaction: if an AFTER trigger fails, the change it was logging is undone too.

Pitfalls of Triggers

Hidden work. Someone reading UPDATE courses ... has no idea a second table changes. Name triggers clearly and document them.

Chains. A trigger's insert can fire another table's triggers, which fire more. Debugging gets hard quickly.

Slow bulk changes. A row trigger runs once per row: updating a million rows runs it a million times.

Business logic in the wrong place. Rules that change often, or need email and web services, belong in application code.

Good uses are narrow ones: audit logs, keeping a cached total in sync, and enforcing rules that constraints can't express.

Triggers in Other Databases

DatabaseRow triggersNotes
PostgreSQLBEFORE, AFTER, INSTEAD OF (on views)Trigger body is a separate function; row- and statement-level
MySQLBEFORE, AFTER with NEW.col, OLD.colRow-level only; body written inside CREATE TRIGGER
SQL ServerAFTER and INSTEAD OFStatement-level only; changed rows are in the inserted and deleted tables
OracleBEFORE, AFTER, INSTEAD OF:NEW and :OLD; row- and statement-level

Tabs showing each database's version are coming to this course.

Once per Row, or Once per Statement

Common Mistakes

Returning NULL from a BEFORE trigger by accident. The row vanishes silently.

Forgetting OF column on update triggers. The trigger fires on every update, even ones that don't touch the column you care about.

Doing heavy work in row triggers. Keep them small and fast.

Assuming triggers fire on TRUNCATE. Row-level delete triggers don't; PostgreSQL has separate TRUNCATE triggers.

Interview Corner

What is a trigger?

Code the database runs automatically when rows in a table are inserted, updated or deleted, before or after the change, once per row or once per statement.

What's the difference between BEFORE and AFTER triggers?

A BEFORE trigger runs before the row is written and can modify or skip it. An AFTER trigger runs once the row is written, so it sees the final row; it's used for logging and follow-up changes.

What are the downsides of triggers?

Hidden side effects, hard-to-follow chains, slower bulk operations and logic spread between the app and the database. Use them for narrow jobs like auditing.

Practice

Challenge (module checkpoint): Build a payment desk. Create a payment_audit table and an AFTER INSERT trigger that logs every new payment. Then create a procedure record_payment(p_student, p_course, p_amount, p_method) that rejects any amount larger than what the student still owes on that course. Record 150.00 for Advitha (102) toward SQL Basics (4), try a second payment of 300.00, and show the audit log.

Show solution
SQL▶ Try it
CREATE TABLE payment_audit (
  audit_id   INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  payment_id INTEGER NOT NULL,
  student_id INTEGER NOT NULL,
  amount_usd NUMERIC(8,2) NOT NULL,
  action     TEXT NOT NULL
);
 
CREATE FUNCTION log_payment() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO payment_audit (payment_id, student_id, amount_usd, action)
  VALUES (NEW.payment_id, NEW.student_id, NEW.amount_usd, TG_OP);
  RETURN NULL;
END;
$$;
 
CREATE TRIGGER payments_audit
AFTER INSERT ON payments
FOR EACH ROW
EXECUTE FUNCTION log_payment();
 
CREATE PROCEDURE record_payment(p_student INTEGER, p_course INTEGER, p_amount NUMERIC, p_method TEXT)
LANGUAGE plpgsql AS $$
DECLARE
  owed NUMERIC;
BEGIN
  SELECT c.fee_usd - COALESCE(sum(p.amount_usd), 0) INTO owed
  FROM courses AS c
  LEFT JOIN payments AS p ON p.course_id = c.course_id AND p.student_id = p_student
  WHERE c.course_id = p_course
  GROUP BY c.fee_usd;
 
  IF p_amount > owed THEN
    RAISE EXCEPTION 'payment of % is more than the % still owed', p_amount, owed;
  END IF;
 
  INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
  VALUES (p_student, p_course, p_amount, DATE '2026-01-05', DATE '2026-01-05', p_method);
END;
$$;
 
CALL record_payment(102, 4, 150.00, 'card');
CALL record_payment(102, 4, 300.00, 'card');
 
SELECT audit_id, payment_id, student_id, amount_usd, action
FROM payment_audit
ORDER BY audit_id;
Output
CREATE TABLE
 
CREATE FUNCTION
 
CREATE TRIGGER
 
CREATE PROCEDURE
 
CALL
 
ERROR:  payment of 300.00 is more than the 250.00 still owed
 
 audit_id | payment_id | student_id | amount_usd | action
----------+------------+------------+------------+--------
        1 |          8 |        102 |     150.00 | INSERT
(1 row)

The first payment passes the check, and the trigger logs it with its new payment id. The second asks for 300.00 when only 250.00 is owed, so the procedure raises an error and nothing is inserted or logged. The procedure enforces the rule; the trigger guarantees the log, even for payments inserted without the procedure.

Quick check: Triggers

3 questions
1Which trigger can change a row before it's saved?
2In an UPDATE trigger, what is OLD?
3A BEFORE row trigger returns NULL. What happens to the row?

Key Takeaways

You want toWrite
Log every changeAFTER INSERT OR UPDATE OR DELETE ... FOR EACH ROW
Clean values firstBEFORE INSERT ... FOR EACH ROW changing NEW
React to one columnAFTER UPDATE OF fee_usd ON courses
Remove a triggerDROP TRIGGER trigger_name ON table_name;

Was this tutorial helpful?

Lesson 86 of 115