SQL · Module 13 · Lesson 22 min read

Functions: SQL & PL/pgSQL

SQL functions – simple and fast

SQL
CREATE FUNCTION spent_in_month(p_user INT, p_month DATE)
RETURNS NUMERIC
LANGUAGE sql STABLE AS $$
  SELECT COALESCE(sum(amount), 0) FROM expenses
  WHERE user_id = p_user AND date_trunc('month', spent_on) = p_month;
$$;
SELECT spent_in_month(1, '2026-11-01');
  • The body is plain SQL; the last statement's result is returned
  • $$ … $$ is dollar quoting (no need to escape single quotes inside)

PL/pgSQL – procedural logic

Variables, IF/ELSE, loops, exceptions:

SQL
CREATE FUNCTION f(...) RETURNS ... LANGUAGE plpgsql AS $$
DECLARE
  v_total NUMERIC;
BEGIN
  SELECT sum(amount) INTO v_total FROM …;
  IF v_total > 1000 THEN … ELSIF … ELSE … END IF;
  RETURN v_total;
EXCEPTION WHEN others THEN …
END $$;
  • SELECT … INTO var, FOUND (did the last statement affect rows?)
  • RAISE NOTICE 'x = %', x; (debug), RAISE EXCEPTION 'message'; (abort with an error)
  • Loops: FOR r IN SELECT … LOOP … END LOOP;

Return types

  • A single value: RETURNS NUMERIC
  • One row: RETURNS users or RETURNS record
  • Many rows: RETURNS SETOF expenses or RETURNS TABLE (name TEXT, total NUMERIC) → use like a table: SELECT * FROM f();
  • Nothing: RETURNS void

Volatility (helps the optimizer)

  • IMMUTABLE – same input → same output forever (pure maths); can be used in indexes
  • STABLE – doesn't change data, same result within one query (reads tables)
  • VOLATILE (default) – may change data or return different results (random(), INSERTs)

Security

  • SECURITY INVOKER (default) – runs with the caller's permissions ✅
  • SECURITY DEFINER – runs with the owner's permissions (powerful, like sudo). Always add SET search_path = public and check inputs carefully.

Why functions?

  • One round trip for multi-step logic (and it runs inside a transaction)
  • Business rules live next to the data
  • Supabase: any function becomes an API endpoint — supabase.rpc('fn_name', { args })

Example

SQL
-- 1. SQL function returning a value
CREATE FUNCTION spent_in_month(p_user INT, p_month DATE)
RETURNS NUMERIC
LANGUAGE sql STABLE AS $$
  SELECT COALESCE(sum(amount), 0)
  FROM expenses
  WHERE user_id = p_user
    AND spent_on >= p_month AND spent_on < p_month + INTERVAL '1 month';
$$;
SELECT name, spent_in_month(id, '2026-11-01') AS nov FROM users ORDER BY nov DESC;

-- 2. Function returning a table
CREATE FUNCTION top_expenses(p_user INT, p_limit INT DEFAULT 3)
RETURNS TABLE (title TEXT, amount NUMERIC, spent_on DATE)
LANGUAGE sql STABLE AS $$
  SELECT e.title, e.amount, e.spent_on FROM expenses e
  WHERE e.user_id = p_user ORDER BY e.amount DESC LIMIT p_limit;
$$;
SELECT * FROM top_expenses(2);
SELECT * FROM top_expenses(p_user => 1, p_limit => 2);   -- named arguments

-- 3. PL/pgSQL with validation and logic: add an expense safely
CREATE FUNCTION add_expense(p_user INT, p_title TEXT, p_amount NUMERIC, p_category TEXT DEFAULT NULL)
RETURNS BIGINT
LANGUAGE plpgsql AS $$
DECLARE
  v_category_id INT;
  v_new_id      BIGINT;
  v_month_total NUMERIC;
  v_budget      NUMERIC;
BEGIN
  IF p_amount <= 0 THEN
    RAISE EXCEPTION 'Amount must be positive (got %)', p_amount;
  END IF;

  SELECT id INTO v_category_id FROM categories WHERE lower(name) = lower(p_category);

  INSERT INTO expenses (user_id, category_id, title, amount)
  VALUES (p_user, v_category_id, trim(p_title), p_amount)
  RETURNING id INTO v_new_id;

  SELECT spent_in_month(p_user, date_trunc('month', CURRENT_DATE)::date), monthly_budget
  INTO v_month_total, v_budget
  FROM users WHERE id = p_user;

  IF v_month_total > v_budget THEN
    RAISE NOTICE 'Heads up: budget exceeded (% of %)', v_month_total, v_budget;
  END IF;
  RETURN v_new_id;
END $$;

SELECT add_expense(1, '  Pizza night ', 1200, 'restaurants') AS new_id;
SELECT title, category_id FROM expenses WHERE title = 'Pizza night';   -- Pizza night | 8

-- Errors are raised to the caller (and roll back the statement)
DO $$ BEGIN PERFORM add_expense(1, 'Bad', -5);
EXCEPTION WHEN others THEN RAISE NOTICE 'Caught: %', SQLERRM; END $$;
-- Caught: Amount must be positive (got -5)

-- In Supabase JS: await supabase.rpc('add_expense', { p_user: 1, p_title: 'Pizza', p_amount: 1200 })