Difficulty: Intermediate
What are database triggers, what are good use cases for them, and what are the risks of relying on them?
A trigger is a function that the database runs automatically when a specific event happens on a table, such as an INSERT, UPDATE or DELETE. Triggers fire inside the same transaction as the statement that caused them, so they can validate, modify or record changes in a way that no application code path can skip. They are great for audit logs, timestamps and denormalized counters, but hidden logic and extra write cost make them risky for general business rules.
A trigger has a few parts:
INSERT, UPDATE (optionally UPDATE OF column), DELETE, and in PostgreSQL also TRUNCATE.BEFORE runs before the row is written and can change or reject it; AFTER runs after and is used for side effects; INSTEAD OF replaces the operation, used on views.FOR EACH ROW fires once per affected row with access to OLD and NEW; FOR EACH STATEMENT fires once per statement.WHEN (...) clause skips the trigger when it is not needed.Vendor notes: PostgreSQL triggers call a trigger function (EXECUTE FUNCTION, which replaced EXECUTE PROCEDURE syntax in v11) and support statement-level triggers with transition tables (REFERENCING NEW TABLE AS). MySQL supports only row-level triggers, with BEFORE and AFTER timing.
OLD and NEW values into an audit_log table on every change to sensitive tables like accounts or kyc_details. Even a manual SQL fix by an engineer gets logged.updated_at = now() in a BEFORE UPDATE trigger. MySQL can do this without a trigger using ON UPDATE CURRENT_TIMESTAMP; PostgreSQL needs a trigger.posts.comment_count or a search tsvector column in sync.CHECK or foreign key cannot express, like "a doctor cannot have overlapping appointments" (though an exclusion constraint may be better in PostgreSQL).pg_notify so other services learn about changes.INSERT and has no idea it also writes three other tables. Debugging gets hard.| Use triggers for | Keep in application code |
|---|---|
| Audit logging | Business workflows and pricing rules |
updated_at timestamps | Anything calling external services |
| Simple denormalized counters | Logic that changes often |
| Last-line integrity checks | Logic the team needs to test easily |
CREATE TABLE audit_log (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
table_name TEXT NOT NULL,
op TEXT NOT NULL,
old_row JSONB,
new_row JSONB,
changed_by TEXT NOT NULL DEFAULT current_user,
changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE OR REPLACE FUNCTION log_change() RETURNS trigger
LANGUAGE plpgsql AS $
BEGIN
INSERT INTO audit_log (table_name, op, old_row, new_row)
VALUES (TG_TABLE_NAME, TG_OP,
CASE WHEN TG_OP <> 'INSERT' THEN to_jsonb(OLD) END,
CASE WHEN TG_OP <> 'DELETE' THEN to_jsonb(NEW) END);
RETURN NULL; -- return value is ignored for AFTER triggers
END;
$;
CREATE TRIGGER accounts_audit
AFTER INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW EXECUTE FUNCTION log_change();
Every change to accounts, from the app or a manual psql session, is recorded with before and after values in the same transaction.
CREATE OR REPLACE FUNCTION set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $
BEGIN
NEW.updated_at := now();
RETURN NEW; -- BEFORE triggers must return the row to write
END;
$;
CREATE TRIGGER orders_set_updated_at
BEFORE UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
A BEFORE trigger edits NEW before it is stored. Returning NULL from a BEFORE row trigger would silently skip the update.
Database Triggers, BEFORE and AFTER Triggers, Row-level vs Statement-level, Audit Logging, Transition Tables