4 Hours

13. Procedural Logic: Functions & Triggers

Server-Side Logic

The Active Database

In a world-class application, the database is not passive. It reacts. Triggers and Stored Functions allow you to automate data auditing, maintain statistics, and enforce complex business rules that application code might miss.

PL/pgSQL: Postgres's Internal Language

PL/pgSQL is a procedural language that allows you to use loops, conditionals, and variables directly inside SQL functions. This is exponentially faster for data-heavy operations because it eliminates the network overhead between your app and the DB.

SQL
-- A function to calculate tax
CREATE OR REPLACE FUNCTION calculate_total(price NUMERIC)
RETURNS NUMERIC AS $$
BEGIN
  RETURN price * 1.15; -- 15% tax
END;
$$ LANGUAGE plpgsql;

Triggers: The Silent Watchers

A Trigger is a function that fires automatically whenever an INSERT, UPDATE, or DELETE occurs. Use them for Audit Logs (who changed what?) or Auto-updating Timestamps.

SQL
CREATE TRIGGER trigger_update_timestamp
BEFORE UPDATE ON profiles
FOR EACH ROW EXECUTE FUNCTION update_modified_at_column();

Step-by-Step: Creating an Audit Log

  1. Log Table: Create a table audit_logs to store changes.
  2. Function: Write a function that inserts the OLD and NEW row values into the log.
  3. Attach: Add a Trigger to your sensitive tables (like accounts) to call that function.

Knowledge Check

Ready to test your understanding of 13. Procedural Logic: Functions & Triggers?

Back