Sub topic 11
Stored procedures, CALL, and transaction control
This chapter assumes you can write a basic PL/pgSQL function, use GET DIAGNOSTICS, and handle errors with EXCEPTION blocks, as covered in earlier chapters. It also assumes you know what a transaction is and what COMMIT and ROLLBACK do. Examples need PostgreSQL 11 or later. Where a feature needs a later version, the text says so.
Why procedures exist
A function runs inside the transaction of the statement that called it. A query such as SELECT my_func() is one statement, so everything the function does commits or rolls back together with it. The function cannot say "commit what I have done so far and carry on."
That is a problem for long maintenance jobs. Moving ten million rows in one transaction holds locks for a long time, produces a large amount of WAL, and loses all progress if it fails near the end. A stored procedure solves this because it can end the current transaction and start a new one while it runs.
Functions and procedures compared
| Aspect | `CREATE FUNCTION` | `CREATE PROCEDURE` |
|---|---|---|
| Invoked with | `SELECT f()`, or inside any expression | `CALL p()` only |
| Return value | Required (`RETURNS`), may be `void` | None. `OUT` and `INOUT` parameters can hand values back |
| Usable in `SELECT`, `WHERE`, indexes | Yes | No |
| `COMMIT` / `ROLLBACK` inside | No | Yes, in PL/pgSQL |
| Volatility (`IMMUTABLE`, `STABLE`) | Yes | Not applicable |
| Usable as a trigger function | Yes | No |
| Drop with | `DROP FUNCTION` | `DROP PROCEDURE` |
Functions and procedures live in the same namespace per signature, but they are different object kinds. DROP FUNCTION will not remove a procedure, and CALL will not run a function.
Creating and calling a procedure
The syntax matches CREATE FUNCTION, minus the RETURNS clause. The procedure below moves old orders into an archive table in batches and commits after each batch. It assumes orders_archive has the same columns as orders.
CREATE PROCEDURE archive_old_orders(p_cutoff date, p_batch integer DEFAULT 1000)
LANGUAGE plpgsql
AS $$
DECLARE
v_moved integer;
BEGIN
LOOP
WITH moved AS (
DELETE FROM orders
WHERE id IN (
SELECT id FROM orders WHERE created_at < p_cutoff 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');Each pass of the loop deletes up to p_batch rows and inserts them into the archive in one statement, so a row is never in both tables or in neither. GET DIAGNOSTICS ... ROW_COUNT reports how many rows the INSERT wrote. When a pass moves nothing, the loop exits. Otherwise COMMIT makes the batch permanent and PostgreSQL silently starts a new transaction for the next pass.
Parameter lists work as they do for functions: named parameters, defaults, and the => named-argument notation all apply to CALL.
Returning values with OUT and INOUT
A procedure has no RETURNS, but it can report results through parameters. INOUT parameters work in all supported versions. OUT parameters in procedures need PostgreSQL 14 or later. CALL returns a single row containing the output values.
CREATE PROCEDURE archive_old_orders_counted(
p_cutoff date,
p_batch integer,
INOUT p_total bigint
)
LANGUAGE plpgsql
AS $$
DECLARE
v_moved integer;
BEGIN
p_total := 0;
LOOP
WITH moved AS (
DELETE FROM orders
WHERE id IN (
SELECT id FROM orders WHERE created_at < p_cutoff LIMIT p_batch
)
RETURNING *
)
INSERT INTO orders_archive SELECT * FROM moved;
GET DIAGNOSTICS v_moved = ROW_COUNT;
EXIT WHEN v_moved = 0;
p_total := p_total + v_moved;
COMMIT;
END LOOP;
END;
$$;
CALL archive_old_orders_counted(date '2025-01-01', 1000, NULL);When you call from SQL, pass a placeholder such as NULL in the INOUT position. The psql output is one row with column p_total. Local variables and parameters keep their values across a COMMIT, so the running total survives each batch.
What COMMIT and ROLLBACK do in a procedure
COMMIT ends the current transaction and makes its changes permanent. ROLLBACK ends it and discards its changes. Either one starts a new transaction immediately. Both are plain PL/pgSQL statements, not SQL you run through EXECUTE.
Two variants matter:
COMMIT AND CHAINandROLLBACK AND CHAINstart the new transaction with the same characteristics (isolation level, read-only flag) as the one that just ended. WithoutAND CHAIN, the new transaction takes the session defaults.- A
ROLLBACKdiscards only work since the last commit. Batches already committed stay.
That second point shapes how you design long procedures. If the procedure fails on batch 400, batches 1 to 399 are committed and remain. Write the work so that running it again is safe. The archive procedure is restartable because it selects only rows still in orders.
Where transaction control is allowed
Transaction control is the main source of errors with procedures. The usual failure is this message:
ERROR: invalid transaction terminationIt appears when the procedure was started in a context that cannot be ended mid-way. The common causes are:
- An explicit transaction block.
BEGIN; CALL archive_old_orders(...);fails at the firstCOMMIT, because the client owns that transaction and the procedure may not end it. RunCALLin autocommit mode. - A call chain that includes a function.
SELECT my_func()wheremy_funccalls a procedure fails, because the function's statement owns the transaction. Procedures can call other procedures, so a chain ofCALLstatements from a top-levelCALLis fine. - A
SETclause on the procedure. A procedure created withSET search_path = ...or anotherSEToption cannot use transaction control. - An enclosing block with an
EXCEPTIONclause. A block withEXCEPTIONruns in a subtransaction, and you cannot commit while one is active. Put theCOMMIToutside that block.
A DO block can also commit, under the same rules as procedures. It is handy for one-off maintenance.
Catching errors and still committing
Rule 4 above does not stop you from handling errors per item. Put the EXCEPTION clause in a nested block and the COMMIT after that block ends. This example assumes a jobs table with id, status, and error columns, and a function process_job(integer) that does the work for one job.
CREATE PROCEDURE process_pending(p_limit integer DEFAULT 100)
LANGUAGE plpgsql
AS $$
DECLARE
r record;
BEGIN
FOR r IN
SELECT id FROM jobs WHERE status = 'pending' ORDER BY id LIMIT p_limit
LOOP
BEGIN
PERFORM process_job(r.id);
UPDATE jobs SET status = 'done' WHERE id = r.id;
EXCEPTION
WHEN OTHERS THEN
UPDATE jobs SET status = 'failed', error = SQLERRM WHERE id = r.id;
END;
COMMIT;
END LOOP;
END;
$$;If process_job raises an error, the inner block rolls back its own changes, marks that one job as failed, and the loop continues. The COMMIT sits after END; of the inner block, so no subtransaction is active when it runs.
Commits inside a loop over a query are allowed. PostgreSQL turns the loop's cursor into a holdable cursor so it survives the commit. The query result is then materialized at the first commit, which costs memory or temporary disk for very large results. For huge sets, prefer the keyset or LIMIT batching used in archive_old_orders.
Locks and visibility across commits
Each COMMIT releases the locks taken in that transaction. A procedure that depends on a lock held for its whole run will not work, because the lock vanishes at the first commit. Take what you need again in each batch.
Other sessions can see committed batches while the procedure is still running. A reader may see some old orders in orders_archive and others still in orders. That is acceptable for archiving. It is not acceptable when readers need all-or-nothing results, and in that case a single function in one transaction is the right tool.
Permissions and maintenance
- Grant
EXECUTE ON PROCEDURE name(argtypes)to let other roles call it. \dfin psql lists functions and procedures. Its type column distinguishes them.- Use
CREATE OR REPLACE PROCEDUREto change a body without dropping dependents. You cannot change the parameter list this way, because a new signature creates a new procedure. - Name the full signature when two overloads exist:
DROP PROCEDURE archive_old_orders(date, integer);.
Choosing between the two
Use a function when the result is a value or a row set that other SQL consumes, when you need a trigger, or when the whole operation must be atomic. Use a procedure when the job is an action that benefits from intermediate commits, such as batch archiving, backfills, or queue processing. If you do not need COMMIT, a function that returns void is often simpler, because it works inside larger transactions and can be called from other functions.
Exercise
A teammate wrote CREATE PROCEDURE purge_logs() ... COMMIT ... and runs it from an application that opens a transaction with BEGIN, calls CALL purge_logs();, then issues COMMIT. The call fails with "invalid transaction termination". Give the cause and two ways to fix it.
Show answer
The procedure tries to commit a transaction that the client opened with an explicit BEGIN, which a procedure may not end. Fix it by running CALL purge_logs(); in autocommit mode with no surrounding BEGIN, or by removing the COMMIT from the procedure so the client controls the transaction. The second fix gives up batch-by-batch commits.
Exercise
In a procedure, you want to catch an error for each row and then commit after every row. You wrote LOOP ... BEGIN ... COMMIT; EXCEPTION WHEN OTHERS THEN ... END; END LOOP; and it fails at the COMMIT. Why, and how do you fix it?
Show answer
The COMMIT is inside a block that has an EXCEPTION clause, and that block runs in a subtransaction, so the commit is not allowed. Move the COMMIT after the END; of the inner block so it runs in the outer block, which has no EXCEPTION clause.
Exercise
archive_old_orders fails with an error during the 400th batch. What state is the data in, and why is it safe to call the procedure again?
Show answer
Batches 1 to 399 were committed, so those rows are in orders_archive and gone from orders. The failed batch is rolled back, so its rows are still in orders. Calling the procedure again selects only rows still in orders older than the cutoff, so it continues where it stopped without duplicating anything.