Sub topic 9
Procedures and CALL
A procedure is a stored routine that you start with CALL instead of SELECT. It is meant for actions, such as archiving rows or recording an event, and not for computing a value inside a query. This chapter assumes you can write a basic SQL function (the earlier chapters on CREATE FUNCTION, parameters and INSERT ... RETURNING) and that you are on PostgreSQL 14 or later. Procedures exist since PostgreSQL 11, but BEGIN ATOMIC bodies and OUT parameters need 14.
How a procedure differs from a function
The two look alike, but they sit in different places in the system.
| Aspect | Function | Procedure |
|---|---|---|
| Created with | `CREATE FUNCTION` | `CREATE PROCEDURE` |
| Invoked with | `SELECT`, or anywhere an expression or table is allowed | `CALL` only |
| `RETURNS` clause | Required (unless `OUT` parameters) | None |
| Result | A value or a set of rows | Nothing, or one row of `OUT`/`INOUT` values |
| Volatility, `STRICT`, `COST`, `ROWS`, `PARALLEL` | Supported | Not supported |
| Usable in `WHERE`, `SELECT` list, `JOIN` | Yes | No |
Because a procedure never appears inside a query, the planner has nothing to optimize around it. That is why the volatility, cost and parallel attributes do not apply. A procedure also cannot be STRICT. It runs even when you pass NULL, so check for NULL yourself if it matters.
Creating and calling a procedure
A SQL procedure runs its statements in order. This one copies old orders to an archive table and then deletes them:
-- Assumes tables orders and orders_archive with identical columns
CREATE PROCEDURE archive_old_orders(cutoff date)
LANGUAGE sql
AS $$
INSERT INTO orders_archive
SELECT * FROM orders WHERE ordered_at < cutoff;
DELETE FROM orders WHERE ordered_at < cutoff;
$$;
CALL archive_old_orders(date '2025-01-01');CALL returns no rows when the procedure has no OUT or INOUT parameters. psql prints just CALL.
The two statements form one unit. If the DELETE fails, the INSERT is undone as well. Both statements also see the same cutoff value. There is one catch: ordered_at is timestamptz and cutoff is date, so the comparison converts the date using the session time zone. Keep that in mind when the cutoff must be exact.
Calling the wrong way
Mixing up SELECT and CALL is the most common error with procedures. PostgreSQL tells you what to do:
SELECT archive_old_orders(date '2025-01-01');
-- ERROR: archive_old_orders(date) is a procedure
-- HINT: To call a procedure, use CALL.The reverse also fails. CALL add_tax(100) reports that add_tax is not a procedure.
Body forms
Procedures accept the same two body forms as functions: a dollar-quoted string, or a BEGIN ATOMIC ... END block. The ATOMIC form is parsed when you create the procedure. It records dependencies on the tables and columns it uses, so typos fail at creation time and not at the first call.
-- Assumes tables users(id int, last_login timestamptz)
-- and login_audit(user_id int, logged_at timestamptz)
CREATE PROCEDURE record_login(p_user_id int, p_at timestamptz DEFAULT now())
LANGUAGE sql
BEGIN ATOMIC
UPDATE users SET last_login = p_at WHERE id = p_user_id;
INSERT INTO login_audit (user_id, logged_at) VALUES (p_user_id, p_at);
END;Parameter defaults work as they do for functions, and CALL accepts positional or named arguments:
CALL record_login(7);
CALL record_login(p_user_id => 7, p_at => timestamptz '2026-11-27 21:00+00');The default now() is evaluated at call time, not at creation time.
Getting values back with OUT and INOUT
A procedure has no return type, but it can hand back one row through OUT and INOUT parameters. For a SQL procedure, the last statement must produce a row whose columns match those parameters. This version reports how many orders it moved. It uses a data-modifying CTE, so deleting and inserting happen in a single statement:
CREATE PROCEDURE archive_orders_before(cutoff date, OUT moved_count bigint)
LANGUAGE sql
AS $$
WITH deleted AS (
DELETE FROM orders WHERE ordered_at < cutoff RETURNING *
), archived AS (
INSERT INTO orders_archive SELECT * FROM deleted RETURNING 1
)
SELECT count(*) FROM archived;
$$;
CALL archive_orders_before(date '2025-01-01', NULL); moved_count
-------------
120
(1 row)Note the NULL in the call. CALL requires an argument for every parameter that has no default, including OUT parameters. PostgreSQL does not evaluate the argument for an OUT slot, so writing NULL is the convention.
If a procedure has no OUT parameters and its last statement is a SELECT, the rows are computed and then thrown away. A procedure cannot return a result set to the client the way a function can.
What happens inside the transaction
CALL runs inside the caller's transaction. The outcomes follow from that:
- Outside an explicit transaction block, the
CALLis its own transaction (autocommit). It commits if every statement succeeds and rolls back entirely if one fails. - Inside
BEGIN ... COMMIT, the procedure's changes become part of your transaction. A laterROLLBACKundoes them.
BEGIN;
CALL archive_old_orders(date '2025-01-01');
ROLLBACK; -- orders and orders_archive are back to their earlier stateNo COMMIT inside a SQL procedure
Procedures in other languages, such as PL/pgSQL, can call COMMIT and ROLLBACK in their bodies. This lets a long batch job commit in chunks. SQL-language procedures cannot. Transaction control commands, including SAVEPOINT, are not allowed in a SQL function or procedure body. If you need batch commits, write the procedure in PL/pgSQL. That choice is covered in the last chapter.
A related limit: CALL cannot run inside a function body unless that function is written in a language that supports it. In a transaction block started by the caller, a procedure that tried to commit would fail.
Security and privileges
Procedures share the security options of functions:
SECURITY DEFINERruns the procedure with the privileges of its owner.SET search_path = ...pins the schema search order for the call.EXECUTEis granted toPUBLICby default.
CREATE PROCEDURE record_login_secure(p_user_id int)
LANGUAGE sql
SECURITY DEFINER
SET search_path = pg_catalog, public
BEGIN ATOMIC
UPDATE users SET last_login = now() WHERE id = p_user_id;
END;
REVOKE EXECUTE ON PROCEDURE record_login_secure(int) FROM PUBLIC;
GRANT EXECUTE ON PROCEDURE record_login_secure(int) TO app_role;Use the keyword PROCEDURE in GRANT, REVOKE, ALTER and DROP. Using FUNCTION for a procedure produces an error. Alternatively, use ROUTINE, which matches either kind.
Common errors
- Using
SELECTto start a procedure. UseCALL. - Forgetting
OUTarguments inCALL. PassNULLfor each one. - Expecting
STRICTbehavior. A procedure runs withNULLarguments. Guard withWHERE p IS NOT NULLor a check in PL/pgSQL. - Putting
COMMITin a SQL body. It is rejected. Switch to PL/pgSQL. - Adding
IMMUTABLE,COSTorPARALLEL SAFE. These are syntax errors onCREATE PROCEDURE. - Relying on a final
SELECTfor output. WithoutOUTparameters its rows are discarded.
Exercise
You wrote CREATE PROCEDURE renamecustomer(pid int, pname text, OUT oldname text) in SQL. The body is a single UPDATE ... SET name = pname WHERE id = pid RETURNING ... that should give back the previous name. Why can a plain UPDATE ... RETURNING name not work as written, and how do you call the procedure for customer 5 and new name 'Grace'?
Show answer
RETURNING on an UPDATE returns the new row values, so name would be 'Grace', not the old name. Capture the old value first, for example with a CTE: WITH old AS (SELECT name FROM customers WHERE id = pid FOR UPDATE), upd AS (UPDATE customers SET name = pname WHERE id = pid) SELECT name FROM old; The last statement then supplies the oldname column. Call it with CALL rename_customer(5, 'Grace', NULL); the NULL stands in for the OUT parameter.
Exercise
A teammate runs CALL archiveoldorders(date '2025-01-01') inside BEGIN, and the DELETE then fails on a foreign key violation. Is any row left in orders_archive after they issue ROLLBACK? What if they had run the CALL outside any transaction block?
Show answer
No. The INSERT and DELETE belong to the same transaction, so the failure and the ROLLBACK undo both. Outside a transaction block the CALL runs as its own autocommit transaction. The failing DELETE aborts it, so the INSERT is rolled back too and no rows reach orders_archive.