Stored Procedure

A stored procedure is a named block of code, typically SQL combined with a procedural extension such as PL/pgSQL, Oracle’s PL/SQL, or SQL Server’s T-SQL, that is stored inside the database server and executed there rather than in the application. In PostgreSQL, “CREATE PROCEDURE defines a new procedure,” and a procedure is invoked with the CALL command rather than being called as part of a query expression.

The point of putting logic in the database is to keep it close to the data: a procedure can run several statements together, loop, branch, and operate on rows without round-tripping each step back to the application. This can reduce network traffic and centralize rules that many applications share.

A defining capability of procedures, as opposed to functions, is transaction control. The PostgreSQL documentation notes the boundary cases explicitly: “A SECURITY DEFINER procedure cannot execute transaction control statements (for example, COMMIT and ROLLBACK, depending on the language),” and likewise “if a SET clause is attached to a procedure, then that procedure cannot execute transaction control statements.” Outside those restrictions, a procedure can commit and roll back transactions itself, which a plain function generally cannot.

The trade-off is that procedural code living inside the database is harder to version, test, and review than ordinary application code. It does not sit naturally in the same source repository or test harness as the rest of the system, so logic hidden in stored procedures can be easy to overlook.