← Back to PostgreSQL Course | Chapter 10: Advanced Features | Lesson 4 of 7

Triggers

A trigger runs a function automatically when a row is inserted, updated or deleted.

In this page:

  1. Triggers
Syntax
sql
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
EXECUTE FUNCTION function_name();

Triggers

A trigger is attached to a table with CREATE TRIGGER ... BEFORE or AFTER INSERT/UPDATE/DELETE and calls a trigger function that returns the special type trigger.

Inside it, NEW and OLD hold the row values. Common uses are audit logs, keeping updated_at current and enforcing complex rules. Triggers add hidden behaviour, so document them.

Note: BEFORE triggers can modify NEW; AFTER triggers are for side effects.

Example: Triggers

bash
shop=# CREATE FUNCTION touch_updated_at() RETURNS trigger LANGUAGE plpgsql AS $$
shop$# BEGIN
shop$#   NEW.updated_at := now();
shop$#   RETURN NEW;
shop$# END $$;
shop=# CREATE TRIGGER trg_users_touch BEFORE UPDATE ON users
shop-#   FOR EACH ROW EXECUTE FUNCTION touch_updated_at();
CREATE TRIGGER
shop=# UPDATE users SET name = 'Ada L.' WHERE id = 1;
UPDATE 1

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Hidden logic surprising other developers
  2. Infinite trigger loops
  3. Heavy work inside triggers
Chapter Summary
  • Triggers fire on INSERT, UPDATE, DELETE
  • NEW and OLD hold row values
  • BEFORE can change the row
  • Use sparingly and document them
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.