Trigger Functions — Complete Guide
Trigger Functions — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 44 of 100
Trigger Functions
SQL ✓ → Advanced
Advanced · 2 — Production · ~6 min · PostgreSQL — Functions & Automation
What is this?
Trigger functions are PL/pgSQL (or other) routines returning TRIGGER type. They access OLD and NEW row records and return NEW (or NULL to cancel in BEFORE triggers).
Why should you care?
PostgresVerse updated_at column stays fresh on every row change without each API developer remembering to set it.
See it live — copy this example
Run in pgAdmin or psql.
CREATE OR REPLACE FUNCTION touch_updated_at()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER trg_products_touch
BEFORE UPDATE ON products
FOR EACH ROW
EXECUTE FUNCTION touch_updated_at();
What happened?
- BEFORE UPDATE assigns NEW.updated_at to current time and returns NEW so update proceeds with fresh timestamp.
- Same function reused on many tables.
Practice next
- Add updated_at timestamptz to products.
- Create function and trigger.
- UPDATE name only; verify updated_at changed.
- Log OLD and NEW json to audit table in trigger function.
- Use TG_OP to branch INSERT vs UPDATE logic.
Remember
RETURNS trigger and special variables OLD/NEW. RETURN NULL skips row change in BEFORE triggers. Share one function across multiple triggers.
PostgresVerse sync timestamps
Mobile cache uses updated_at for delta sync across products and orders.
Outcome: Cache invalidation works even for admin SQL fixes in pgAdmin.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!