Sub topic 14
Performance, Testing, and Maintenance
This chapter assumes you know basic SQL, PostgreSQL data types, and PL/pgSQL functions. You should also be able to run statements in psql or another SQL client and understand variables, conditions, and loops.
PL/pgSQL runs inside PostgreSQL, so it can avoid network round trips between an application and the database. That does not make every PL/pgSQL function fast. The same rules still apply: read only the rows you need, use indexes, avoid unnecessary loops, and measure real execution time.
Prefer set-based SQL
A set-based query processes a group of rows in one SQL operation. A loop processes rows one at a time. The set-based form is usually shorter and faster.
CREATE OR REPLACE FUNCTION customer_total(p_customer_id integer)
RETURNS numeric
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_total numeric;
BEGIN
SELECT COALESCE(sum(o.total), 0)
INTO v_total
FROM orders AS o
WHERE o.customer_id = p_customer_id;
RETURN v_total;
END;
$$;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_total(42);EXPLAIN shows the query plan chosen by PostgreSQL. ANALYZE runs the statement and adds actual timing and row counts. BUFFERS shows whether PostgreSQL read data from memory or from disk.
Compare estimated rows with actual rows. A large difference can indicate stale statistics, skewed data, or a query whose conditions are difficult to estimate. Run performance tests against representative data. A function that is fast with ten rows may be slow with ten million.
Test behavior and failure paths
Test successful results, empty results, invalid inputs, and expected errors. A simple DO block can act as a lightweight assertion test without installing another extension.
DO $$
DECLARE
v_actual numeric;
BEGIN
SELECT customer_total(42) INTO v_actual;
IF v_actual < 0 THEN
RAISE EXCEPTION 'customer total must not be negative: %', v_actual;
END IF;
IF customer_total(NULL) IS NOT NULL THEN
RAISE EXCEPTION 'NULL input should return NULL';
END IF;
END;
$$;If the function should reject a missing customer, test that contract explicitly. Test exception messages only when callers depend on them. Prefer SQLSTATE codes for stable error handling.
A transaction gives a safe boundary for tests that write data:
BEGIN;
SELECT archive_old_orders(date '2025-01-01', 10);
-- Inspect the expected changes here.
ROLLBACK;Procedures that issue COMMIT cannot run inside this kind of explicit transaction. Test those procedures in a disposable database or with test data that can be restored.
Maintainable database code
Keep each function focused on one operation. Give parameters a consistent prefix such as p_, local variables a prefix such as v_, and query records a prefix such as r_. Qualify column names with table aliases so they cannot be confused with parameters or output variables.
Document assumptions that affect safety or performance:
- required indexes and constraints
- whether the function can change data
- expected row counts
- volatility and security settings
- transaction behavior
- error conditions and SQLSTATE values
Store function definitions in version-controlled migration files. Use CREATE OR REPLACE FUNCTION when the signature stays compatible. Changing a parameter type or return type often requires dropping and recreating the function, which can affect dependent objects. Apply such changes in a planned migration.
A repeatable checklist
Before releasing a function or procedure, confirm:
- The return type matches every return path.
SELECT INTO,FOUND, andGET DIAGNOSTICSare used intentionally.- Empty results and duplicate results have defined behavior.
- Loops are necessary instead of replaceable by one SQL statement.
- Dynamic identifiers use
format('%I', ...), and values useUSING. - Volatility and
SECURITY DEFINERsettings reflect actual behavior. - Tests cover both success and failure.
- The migration can be applied consistently to a new database.
Exercise
A function loops through every order for a customer and adds each total to a variable. What should you investigate first?
Show answer
Look for a set-based aggregate such as SELECT COALESCE(sum(total), 0). Then compare both versions with EXPLAIN (ANALYZE, BUFFERS) using representative data.