Functions and procedures: choose the call boundary
Trace a stored function and procedure through their inputs, effects, return paths, and qualified transaction boundaries. Routines and trigger execution · Databases.
A dashboard needs one account balance. A transfer endpoint needs two updates and a clear failure path. Storing both operations in the database can reduce duplicated SQL, but only if you name what the call returns, what it changes, and which transaction owns the boundary.
Start with the call boundary
Use these tables: accounts(account_id, balance) with rows (1, 100) and (2, 40). A function account_balance(p_id) reads one balance and returns a numeric value. A procedure transfer(p_from, p_to, p_amount) checks both accounts, subtracts from one, and adds to the other. The procedure has effects; the function is used as a value in a larger statement.
Trace function values and procedure effects
Read the steps as text
- PostgreSQL 18 accounts are transactional: (1,100) and (2,40). account_balance(1) reads a value; transfer(1,2,25) changes two rows. No caller transaction has started.
- SELECT uses an expression value; CALL invokes an operation. The caller has staged BEGIN; CALL transfer(1,2,25), with 75 and 65 visible before the pending COMMIT.
- The caller owns the COMMIT for 75 and 65. A separate PG18 BEGIN now tries transfer(1,2,120) against fresh accounts (100, 40), without a handler.
- The transfer check rejects 120 before either update. With no handler, the PostgreSQL transaction is aborted until rollback.
- A function supplies an expression value; a procedure changes rows in its session context. Caller, engine, and error handling define the transaction boundary.
The first frame shows the two rows and a caller that has not started a transaction. The function call SELECT account_balance(1) can return 100, but it does not mean that a later transfer committed. The next frame shows CALL transfer(1, 2, 25) as an operation call. In PostgreSQL, a function can be used in an expression and a procedure is invoked with CALL. MySQL makes the same high-level distinction: a stored function returns a scalar in an expression, while CALL invokes a procedure and can expose output parameters or result sets.
Now place the transfer inside an explicit caller transaction: BEGIN; CALL transfer(1, 2, 25); COMMIT;. The intermediate state is (1, 75) and (2, 65) for the transaction's view. The important question is not whether the procedure has a magic private transaction. Its statements run in the session's transaction context unless the named engine and call stack permit transaction control inside the procedure. The caller's COMMIT is the visible durability boundary in this example. A returned value is not itself a commit acknowledgement. Here CALL is inside the caller's explicit block, so transfer leaves commit to the caller; the procedure does not commit that block.
PostgreSQL 18 procedures can execute transaction control only when a top-level CALL or eligible nested CALL/DO chain is not running inside an explicit transaction block and has no intervening command; a procedure reached through SELECT cannot use that path. A SECURITY DEFINER procedure or one with a SET clause also cannot execute transaction control. MySQL permits transaction statements in procedures but forbids explicit commit or rollback in stored functions. These are engine contracts, not a universal “procedure starts a transaction” rule.
Follow failure through the same transaction
Imagine transfer(1, 2, 120). The first debit would make account 1 negative, so a check can reject before either update. If the procedure instead updates account 1 and then discovers that account 2 is missing, the statement or transaction outcome depends on the engine, table type, exception handler, and caller boundary. PostgreSQL reports an error that aborts the current transaction until it is rolled back or handled in a subtransaction. MySQL rolls back a failed statement for transactional tables, while an outer transaction and its handler still determine what follows. A lesson can therefore promise atomic transfer only when the procedure's checks, table engine, error handling, and caller transaction support that promise.
A function that performs a lookup can be marked read-oriented in a named engine, but do not infer purity from the word “function.” PostgreSQL distinguishes IMMUTABLE, STABLE, and VOLATILE; side effects require the conservative profile. MySQL function declarations also carry data-access and determinism characteristics, with restrictions that matter for logging. These properties guide the engine; they do not turn an unsafe declaration into a safe operation.
Keep dynamic SQL split into values and names
Suppose an administrator chooses a report column and a minimum balance. The minimum balance is a value and belongs in a bound parameter. A table or column name is an identifier and cannot be supplied as an ordinary value parameter, so the routine must choose it from a fixed allow-list and quote it with the engine's identifier mechanism. Concatenating either input directly makes the SQL text depend on untrusted text.
PostgreSQL's SECURITY DEFINER adds a second qualification: use a trusted search_path and qualify intended objects as appropriate, because untrusted schemas or temporary objects can mask names. PostgreSQL also resolves functions and operators, so qualifying only a table name is not a complete defense. This is a narrow execution-context warning; privilege design belongs to the access-control lesson.
Keep dynamic values and identifiers separate
Read the steps as text
- ledger(entry_id,account_id,amount,posted_at) has (91,1,25,2026-10-20) and (92,2,-10,2026-10-20). PG18 report_totals(p_column,p_floor) is SECURITY DEFINER; floor 20 and name amount or posted_at are supplied, with lookup policy withheld.
- Bind the numeric floor as a value. Allow-list and quote the column name separately; a chosen column must also be compatible with the comparison.
- The report uses a trusted search_path and qualified table name. A separate call reads ledger and then raises without a handler.
- PG18 runs BEGIN; SELECT report_totals('amount',20); with autocommit off and no handler. The routine reads ledger, then raises before returning a report value.
- Values are bound, names are allow-listed identifiers, and SECURITY DEFINER resolution is qualified. A routine error and absent result still require the named transaction state.
The faded dataset uses ledger(entry_id, account_id, amount, posted_at) and report_totals(p_column, p_floor). The first beat compares a safe value parameter with an unsafe string concatenation. The second considers an identifier allow-list; a selected column must also have a type compatible with the intended comparison. The final beat shows a failed routine call: an exception prevents the promised report result, but the surrounding commit decision still belongs to the engine and caller. No scene declares a universal fastest plan or a universal rollback scope.
Recap
- Functions are expression values; procedures are explicit operation calls with output and side-effect paths.
- Routine statements inherit a transaction context; procedure transaction control is engine- and call-stack-specific.
- Bind values, allow-list identifiers, and treat routine errors and security context as explicit premises.
Why this stops before packages and job schedulers
Some systems add packages, autonomous transactions, events, or language runtimes. Those features change dependency, deployment, and transaction questions enough to deserve separate engine lessons. This lesson keeps the portable reasoning boundary visible and uses PostgreSQL 18 and MySQL 8.4 only where their documented rules clarify it.
Next, Triggers: execution and effect boundaries moves the call boundary from an explicit client invocation to a table event. Practise the trace discipline in Queue Fundamentals: one item can be returned while later work remains in the queue.