📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PostgreSQL Essentials Triggers

Triggers

7 min read
Triggers run a function automatically before or after INSERT, UPDATE, or DELETE on a table. Use them for audit logging and auto-updating timestamps. Define the trigger function in PL/pgSQL first, then the trigger.

Triggers

CREATE OR REPLACE FUNCTION log_update()
RETURNS TRIGGER AS $$
BEGIN
  INSERT INTO audit(table_name, action, changed_at)
  VALUES (TG_TABLE_NAME, TG_OP, NOW());
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER users_audit
AFTER UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION log_update();