# Topic 39: Stored Procedures & Functions
User-Defined Functions (UDFs), stored procedures, transaction control inside procedures, and PL/pgSQL basics.
1. Definition
Functions and Stored Procedures are compiled subroutines stored in the database catalog that encapsulate complex business logic and database operations.
2. Explain Like I'm 5
Instead of sending 20 separate queries back and forth across the internet, you save a program directly inside the database server and run it with one command.
3. Animation & Visual Simulation
Interactive Engine TraceStored Procedures & Functions Visual Simulator
CREATE PROCEDURE archive_old_logs()
LANGUAGE sql
AS $$
DELETE FROM logs WHERE created_at < NOW() - INTERVAL '1 year';
$$;
CALL archive_old_logs();Active InputStep 1: Input & Parsing Stage
Initiating Stored Procedures & Functions
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
A fund transfer operation that deducts money from account A, adds it to account B, logs the transaction, and commits.
| Construct | Can Return Value? | Can Commit/Rollback? | Calling Syntax |
|---|---|---|---|
| FUNCTION | Yes (MANDATORY) | No (Runs inside caller TX) | SELECT my_func() |
| PROCEDURE | No (Optional INOUT) | Yes (Can COMMIT/ROLLBACK) | CALL my_proc() |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectCREATE OR REPLACE FUNCTION calculate_tax(subtotal NUMERIC, tax_rate NUMERIC) RETURNS NUMERIC LANGUAGE plpgsql IMMUTABLE AS $$ BEGIN RETURN ROUND(subtotal * tax_rate, 2); END; $$;
CREATE OR REPLACE PROCEDURE transfer_funds( sender_id INT, receiver_id INT, amount NUMERIC ) LANGUAGE plpgsql AS $$ BEGIN UPDATE accounts SET balance = balance - amount WHERE id = sender_id; UPDATE accounts SET balance = balance + amount WHERE id = receiver_id; COMMIT; END; $$; -- Invoke with CALL: CALL transfer_funds(101, 102, 50.00);
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Procedure Invocation | Procedures are executed using CALL proc_name(); Functions are executed with SELECT func_name(). |
| Transaction Control | Procedures support internal COMMIT and ROLLBACK; Functions run within the caller’s transaction. |
| Volatility Categories | Functions are marked VOLATILE (default), STABLE (reads database), or IMMUTABLE (pure function). |
| Transaction control in procedures | Stored Procedures (CALL) can commit and rollback transactions; User-Defined Functions (SELECT) cannot. |
| Function volatility categories | Functions are marked IMMUTABLE (cacheable), STABLE (constant per statement), or VOLATILE (re-evaluated per row). |
7. Deep Dive: Function Volatility Categories and Query Optimization
Marking a function IMMUTABLE informs the query optimizer that identical arguments always produce identical output without reading tables. The optimizer evaluates the function once at plan time (constant folding) and allows expression indexes.
-- IMMUTABLE: Can be pre-computed at plan time and indexed: CREATE FUNCTION normalize_sku(text) RETURNS text AS $$ ... $$ IMMUTABLE; CREATE INDEX idx_sku ON products(normalize_sku(sku));
8. Advantages & Disadvantages
Advantages
- •Zero network round-trip overhead for multi-step database operations.
- •Enforces uniform logic across multiple programming language backends.
Disadvantages & Trade-offs
- •Difficult to version control, test, and debug compared to standard application code.
9. Common Interview Questions
Q1.What is the critical architectural difference between a Stored Procedure and a User-Defined Function (UDF)?
1. Transaction Control: A Stored Procedure (invoked via CALL proc()) can manage transaction boundaries internally, executing COMMIT and ROLLBACK statements inside its loop. A Function (invoked via SELECT func()) runs strictly inside the caller’s transaction and CANNOT execute COMMIT or ROLLBACK. 2. Return values: Functions must return a value; procedures can return zero or multiple values.
Q2.What are the three Function Volatility categories in PostgreSQL and why do they matter for indexing?
1. IMMUTABLE: Cannot modify database and always returns the exact same result for identical arguments (e.g. UPPER(x)); ONLY immutable functions can be used in Expression Indexes. 2. STABLE: Cannot modify database, result depends on current transaction/table data (e.g. CURRENT_TIMESTAMP or table lookups); optimizer evaluates once per statement. 3. VOLATILE: Can return different values even within a single statement (e.g. random() or timeofday()); optimizer must re-evaluate for every single row.
Q3.What are the security and maintenance trade-offs of embedding business logic in database procedures?
Advantages: 1. Minimizes network round-trips for multi-step mutations, 2. Centralizes security and authorization in the database layer. Disadvantages: 1. Hard to unit-test and version-control compared to standard application code, 2. Database CPU is expensive and difficult to scale horizontally compared to stateless application servers, 3. Vendor lock-in between PL/pgSQL, T-SQL, and PL/SQL.
Q4.What is the difference between SECURITY DEFINER and SECURITY INVOKER functions?
SECURITY INVOKER (the default) executes the function with the privileges of the user who calls it. SECURITY DEFINER executes the function with the elevated privileges of the user who created it (similar to setuid in Linux). In production, SECURITY DEFINER functions must explicitly set a safe search_path to prevent malicious privilege escalation attacks.
Q5.How does plan caching work for stored procedures and functions?
When a PL/pgSQL function or procedure executes, the engine compiles execution plans for internal SQL queries. For the first 5 executions, it generates custom plans based on parameter values. If the generic plan is almost as fast as custom plans, it caches the generic execution plan permanently for the database session, saving planning time on subsequent calls.
10. Interview-Ready Answer
“Functions return values and execute inside the caller’s transaction, while Stored Procedures are invoked with CALL and can manage autonomous transaction commits. Marking pure functions as IMMUTABLE unlocks optimizer constant folding and expression indexing.”
11. Quick Test
Which SQL statement invokes a Stored Procedure in modern PostgreSQL?