Overview

Databases can run code next to the data: functions (return a value or table, usable inside queries), procedures (called with CALL/EXEC, may manage transactions) and triggers (run automatically on data changes). The languages are PL/pgSQL (PostgreSQL), T-SQL (SQL Server) and PL/SQL (Oracle).

Core concepts

  • Routines save round trips and centralise rules, but hide logic from application code, version control and tests unless you manage them like code.
  • Functions have volatility in PostgreSQL (IMMUTABLE, STABLE, VOLATILE), which the optimizer uses. Procedures can COMMIT inside (PostgreSQL 11+).
  • Triggers fire BEFORE/AFTER (or INSTEAD OF) a row or statement event. They are invisible to callers, easy to forget, and run inside the writing transaction.
  • Security: routines can run with the caller’s rights or the owner’s (SECURITY DEFINER in PostgreSQL, EXECUTE AS in SQL Server, definer rights in Oracle). Owner-rights routines are a controlled way to grant narrow access, and a privilege-escalation risk if they build SQL from input or leave search_path open.

Worked example

A set-returning SQL function in PostgreSQL 17 (executed):

CREATE FUNCTION order_total(p_customer int) RETURNS numeric
LANGUAGE sql STABLE AS $$
  SELECT coalesce(sum(amount), 0) FROM big WHERE customer_id = p_customer
$$;
 
SELECT order_total(42);

STABLE tells the planner the result is constant within one statement for the same arguments.

Pitfalls and production notes

  • Row-by-row procedural loops are slow; express work as one set-based statement where possible.
  • Scalar functions called per row can dominate a query. SQL Server before 2019 executes scalar UDFs row by row; version 2019 can inline many of them.
  • Always parameterise dynamic SQL; never concatenate user input.
  • Keep triggers small and few; avoid business workflows in them. Audit and timestamp maintenance are good uses.
  • Deploy routine changes through migrations (safe-schema-migrations) and test them like application code.

Practice questions

  1. When is a trigger the right place for a rule, and when is it a trap?
  2. What is the risk of SECURITY DEFINER without a fixed search_path?
  3. Why can a scalar function in WHERE prevent an index from being used?

References

transactions-acid · query-planning · safe-schema-migrations · pg-security-roles · oracle-plsql