Sub topic 14
Performance, testing, and maintenance
This chapter assumes you can write PL/pgSQL functions with variables, control flow, SELECT INTO, RETURN QUERY, and exception blocks. It also assumes you have read the chapters on function attributes, query loops, and dynamic SQL. Here you learn to find out whether a function is fast, to test it, and to keep it maintainable over time.
Where PL/pgSQL time goes
A PL/pgSQL function is an interpreter that drives the SQL engine. Two kinds of cost matter.
- SQL cost. Each embedded statement is planned and executed like any other query. A slow query inside a function is slow for the same reasons it is slow outside one: a missing index, bad statistics, or a poor join order.
- Interpreter cost. Each assignment, loop iteration, and expression evaluation goes through the PL/pgSQL executor. This is small for one call, but it adds up when a loop runs a million times.
The most common performance problem is not the interpreter itself. It is a loop that runs one small query per row, so the function makes N round trips between PL/pgSQL and the SQL executor where one set-based statement would do.
Prefer set-based statements to row loops
Compare the loop version of total_for_customer with its set-based form.
CREATE FUNCTION total_for_customer_loop(p_customer_id integer)
RETURNS numeric
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
r record;
v_sum numeric := 0;
BEGIN
FOR r IN
SELECT o.total FROM orders o WHERE o.customer_id = p_customer_id
LOOP
v_sum := v_sum + r.total;
END LOOP;
RETURN v_sum;
END;
$$;
CREATE FUNCTION total_for_customer_sql(p_customer_id integer)
RETURNS numeric
LANGUAGE sql
STABLE
AS $$
SELECT coalesce(sum(o.total), 0)
FROM orders o
WHERE o.customer_id = p_customer_id;
$$;Both return the same answer. The second hands the whole job to the database, which can use an index, a parallel plan, or an aggregate node. It is also a simple LANGUAGE sql function, so the planner can sometimes inline it into the calling query. Inlining lets the planner treat the body as part of the outer statement. The conditions are strict: the function must be a single SELECT, not SECURITY DEFINER, and must carry no SET clause.
Use a loop when you genuinely need row-by-row logic, such as calling a side effect per row or branching on complex state. Otherwise write one statement.
Measuring a function
Do not guess. Measure at three levels.
Time the whole call with EXPLAIN ANALYZE
EXPLAIN ANALYZE on a query that calls your function shows the total time, but the function body appears as a single opaque step.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders_over(500);This tells you whether the function as a whole is the bottleneck. It does not tell you which statement inside it is slow.
See inside with auto_explain
The auto_explain module logs the plans of statements that run inside functions. Load it for one session and turn on nested statement logging.
LOAD 'auto_explain';
SET auto_explain.log_min_duration = 0;
SET auto_explain.log_analyze = on;
SET auto_explain.log_nested_statements = on;
SELECT * FROM orders_over(500);The plan of every statement inside orders_over now appears in the server log. Setting log_min_duration to 0 logs everything, so use it only in a test session. In production, set it to a threshold such as 250 ms. LOAD normally requires superuser rights.
Find hot functions with track_functions
PostgreSQL can count calls and time spent per function. The setting track_functions accepts none, pl, or all.
SET track_functions = 'pl';
SELECT * FROM orders_over(500);
SELECT funcname, calls, total_time, self_time
FROM pg_stat_user_functions
ORDER BY total_time DESC;total_time includes time spent in functions this function called. self_time does not. A function with a high total_time but a low self_time is slow because of what it calls, so look further down the call tree. Statistics are collected per session and flushed to the shared view, so a very short session may not show its counts immediately.
Plans, caching, and generic plans
PL/pgSQL caches the plan of each embedded SQL statement within a session. For the first five executions, PostgreSQL plans the statement using the actual parameter values (a custom plan). After that, it may switch to a generic plan that ignores parameter values if the generic plan does not look much more expensive than the average custom plan.
This is normally a win because it skips repeated planning. It can hurt when data is skewed. Suppose 95% of rows have status = 'done' and 0.1% have status = 'failed'. A generic plan cannot know which value you pass, so it may choose a sequential scan that is right for done and terrible for failed.
Symptoms: a function that is fast for the first few calls in a session and then becomes slow, or a function that is slow while the same query typed by hand is fast. To confirm, compare the plan from auto_explain with the plan of the query run manually using literal values.
Fixes, from least to most invasive:
- Update statistics with
ANALYZEon the table. - Add or adjust an index so that both plans are acceptable.
- Use
EXECUTEwithUSINGfor the affected statement so it is planned each time with the real values. - Set
plan_cache_mode = force_custom_planfor the function withALTER FUNCTION ... SET plan_cache_mode = force_custom_plan.
ALTER FUNCTION orders_over(numeric)
SET plan_cache_mode = force_custom_plan;Note that a SET clause on a function prevents inlining of LANGUAGE sql functions, so apply it only where needed.
Volatility affects speed
The volatility marker you chose earlier is a performance setting as well as a correctness one.
| Marker | Meaning | Performance effect |
|---|---|---|
| `IMMUTABLE` | Same arguments always give the same result, with no database lookups | Can be evaluated once at plan time with constant arguments, and used in expression indexes |
| `STABLE` | Same result within one statement | Can be used in index conditions and called fewer times |
| `VOLATILE` | Result may change at any time, may have side effects | Called for every row, blocks many optimizations |
Mark a function with the strictest honest label. A wrong IMMUTABLE is worse than none: the planner may cache a result that later changes, or an expression index may hold values that no longer match what the function returns. A function that reads a table is at most STABLE. A function that calls now() is at most STABLE.
Common slow patterns
- Function calls in a
WHEREclause on a large table. AVOLATILEfunction in a predicate runs once per row and cannot use an index. Mark itSTABLEorIMMUTABLEif that is true. - Row-by-row inserts in a loop. Replace them with
INSERT ... SELECT. - Exception blocks in hot loops. A
BEGIN ... EXCEPTIONblock creates a subtransaction on each entry. This is cheap once and expensive millions of times, and it can contribute to subtransaction overflow on busy systems. Check conditions withIForINSERT ... ON CONFLICT DO NOTHINGinstead of catching the error. - String building for dynamic SQL inside loops. Planning cost repeats on every
EXECUTE. Hoist the work outside the loop if the statement shape does not change. - Calling a function per row from another function. Look for a set-returning version that processes all rows at once.
CREATE FUNCTION add_customer_if_missing(p_email text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO customers (email)
VALUES (p_email)
ON CONFLICT (email) DO NOTHING;
END;
$$;This runs without a subtransaction and without an error path. It assumes customers has a unique constraint on email.
Testing PL/pgSQL code
Database code is code. It needs tests that run automatically and fail loudly.
Start with plain assertions
PL/pgSQL has an ASSERT statement. It raises an error with SQLSTATE P0004 when its condition is false or null. Assertions are enabled by default and controlled by plpgsql.check_asserts.
DO $$
BEGIN
ASSERT add_tax(100) = 120.00, 'default tax should give 120.00';
ASSERT add_tax(100, 0.07) = 107.00, 'explicit rate should give 107.00';
END;
$$;If either assertion fails, the DO block aborts with your message. This is enough for a small smoke test run from a shell script with psql -v ON_ERROR_STOP=1 -f tests.sql.
Test inside a transaction that rolls back
Tests that write data should not leave it behind. Wrap them in a transaction and finish with ROLLBACK.
BEGIN;
INSERT INTO customers (id, email) VALUES (9001, '[email protected]');
DO $$
BEGIN
ASSERT get_customer_email(9001) = '[email protected]';
BEGIN
PERFORM get_customer_email(9002);
ASSERT false, 'expected an error for a missing customer';
EXCEPTION
WHEN raise_exception THEN
NULL;
END;
END;
$$;
ROLLBACK;The inner block catches the error that get_customer_email raises for a missing customer. If no error occurs, the ASSERT false fails. Because the assertion error has a different SQLSTATE (P0004), the WHEN raise_exception handler does not swallow it.
Remember that procedures with COMMIT cannot run inside this wrapper. Test those against a scratch database or a schema you can drop, and check the resulting rows afterwards.
Use a test framework for larger suites
For a real project, use pgTAP. It provides functions such as is(), throws_ok(), and results_eq(), and it produces TAP output that CI tools understand. Run the suite on every change against a freshly built database. Test these cases for each function:
- the normal path,
- NULL inputs (and
STRICTbehavior if you set it), - the empty result and the many-row result,
- each error you raise on purpose,
- permissions, if the function is
SECURITY DEFINER.
Maintenance
Keep definitions in version control
Treat CREATE OR REPLACE FUNCTION scripts as source code. Store each function in a file, review changes, and apply them through a migration tool. CREATE OR REPLACE keeps the function's OID, grants, and dependents, but it cannot change the return type or the names and types of input parameters. In those cases, drop and recreate the function, or add a new overload and migrate callers.
Watch for overload and search_path surprises
Two functions with the same name and different parameter types are both valid. A change in an argument's type can silently route a call to a different overload. List overloads before you change a signature.
SELECT p.oid::regprocedure AS signature, p.prokind, p.provolatile
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public'
AND p.proname = 'add_tax';The prokind column is f for a function and p for a procedure. provolatile is i, s, or v.
For SECURITY DEFINER functions, always pin the search path so that a caller cannot shadow your tables with their own objects.
ALTER FUNCTION get_customer_email(integer)
SET search_path = public, pg_temp;Check code before it runs
PL/pgSQL checks syntax when you create a function but not whether the tables and columns it names exist. A misspelled column fails only when that line runs, which may be in production. The plpgsql_check extension performs a deeper static check, including unknown columns, unused variables, and type mismatches. Run it in CI.
CREATE EXTENSION IF NOT EXISTS plpgsql_check;
SELECT * FROM plpgsql_check_function('orders_over(numeric)');The extension is not part of core PostgreSQL, so confirm it is available on your host before relying on it.
Track dependencies
PostgreSQL does not record which tables a PL/pgSQL function body uses. Dropping a column does not warn you that a function reads it. Keep a test that calls each function after every schema migration, and run plpgsql_check_function against all of them. A query over pg_proc with prolang set to the PL/pgSQL language gives you the list to check.
SELECT p.oid::regprocedure AS routine
FROM pg_proc p
JOIN pg_language l ON l.oid = p.prolang
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE l.lanname = 'plpgsql'
AND n.nspname = 'public'
ORDER BY 1;A review checklist
Before you ship a function, ask:
- Could one SQL statement replace the loop?
- Is the volatility label honest and as strict as possible?
- Are
SECURITY DEFINERfunctions pinned to a safesearch_path? - Does each error path have a test?
- Has
plpgsql_check_functionor an equivalent run clean after the last schema change?
Exercise
A function that looks up an order status runs in 2 ms for the first five calls in a session, then takes 800 ms on later calls. The same query typed by hand with the same value runs in 2 ms. What is the likely cause, and what are two ways to fix it?
Show answer
PostgreSQL probably switched from a custom plan to a generic plan after the fifth execution. With skewed data, the generic plan can be a poor fit for the value being passed. Fixes: run the statement through EXECUTE ... USING so it is planned with the real value each time, or set plancachemode = forcecustomplan on the function with ALTER FUNCTION. Updating statistics with ANALYZE or adding a better index also helps.
Exercise
You write a test with BEGIN, several ASSERT statements in a DO block, and ROLLBACK. Why can you not use this pattern to test a procedure that calls COMMIT in a loop, and what do you do instead?
Show answer
A procedure cannot COMMIT when it is called inside an explicit transaction block, so the CALL fails. Run the test against a scratch database or schema, call the procedure outside a transaction block, check the resulting rows with assertions, and then drop or rebuild the scratch data.