Sub topic 11
Stored Procedures, `CALL`, and Transaction Control
This chapter assumes you know basic SQL transactions, PL/pgSQL blocks, variables, and exception handling. You will learn when to use a stored procedure instead of a function and how transaction control changes the way you call it.
Functions and procedures have different jobs
A PL/pgSQL function computes a value or returns rows. You call it inside a SQL statement, such as SELECT calculate_total(42). A function cannot issue transaction commands such as COMMIT or ROLLBACK.
A procedure performs an operation. You invoke it with the CALL statement. A procedure does not need to return a value, but it can have output parameters. Unlike a function, a procedure can control transactions when PostgreSQL allows it.
| Object | Invocation | Must return a value? | Can commit? |
|---|---|---|---|
| Function | `SELECT` or another SQL expression | Yes, possibly a set of rows | No |
| Procedure | `CALL` | No | Yes, with restrictions |
Use a function for reusable calculations and queries. Use a procedure for workflows that perform several steps, especially when each step should become a separate transaction.
A procedure that commits batches
Suppose orders contains old orders and orders_archive has the same columns. This procedure moves old rows in batches:
CREATE PROCEDURE archive_old_orders(
p_cutoff date,
p_batch integer DEFAULT 1000
)
LANGUAGE plpgsql
AS $$
DECLARE
v_moved integer;
BEGIN
IF p_batch < 1 THEN
RAISE EXCEPTION 'batch size must be positive';
END IF;
LOOP
WITH moved AS (
DELETE FROM orders
WHERE id IN (
SELECT id
FROM orders
WHERE created_at < p_cutoff
ORDER BY id
LIMIT p_batch
)
RETURNING *
)
INSERT INTO orders_archive
SELECT * FROM moved;
GET DIAGNOSTICS v_moved = ROW_COUNT;
EXIT WHEN v_moved = 0;
COMMIT;
END LOOP;
END;
$$;
CALL archive_old_orders(date '2025-01-01');The common table expression named moved deletes one batch and exposes the deleted rows through RETURNING. The INSERT copies those rows to the archive. GET DIAGNOSTICS stores the number of inserted rows in v_moved. When that number is zero, no old rows remain.
COMMIT ends the current transaction. PostgreSQL starts a new transaction for the next loop iteration. If the process fails after an earlier commit, those earlier batches stay committed. This reduces the size of each transaction, but the operation is no longer all-or-nothing.
Transaction-control rules and common errors
Call a procedure that commits outside an explicit transaction block:
CALL archive_old_orders(date '2025-01-01');Do not wrap that call in BEGIN and COMMIT when the procedure itself commits:
BEGIN;
CALL archive_old_orders(date '2025-01-01');
COMMIT;This fails because transaction control is not allowed in that call context. A procedure also cannot commit while running inside a PL/pgSQL block that has an EXCEPTION handler. Keep transaction boundaries outside such blocks, or redesign the operation.
A function remains the right choice when callers need to compose the result with other SQL:
CREATE FUNCTION order_count(p_cutoff date)
RETURNS bigint
LANGUAGE sql
STABLE
AS $$
SELECT count(*)
FROM orders
WHERE created_at < p_cutoff;
$$;
SELECT order_count(date '2025-01-01');Choose procedures carefully. Batch commits improve recovery and reduce lock duration, but they can leave a partially completed workflow. If every change must succeed or fail together, use a function or an ordinary transaction controlled by the caller.
Exercise
Why can archive_old_orders use COMMIT, while a function that performs the same loop cannot?
Show answer
PostgreSQL permits transaction control in procedures called with CALL, but functions execute as part of the statement that invokes them and cannot commit or roll back that transaction.