11. Stored Procedures and Functions
Description
A stored procedure is a set of SQL statements stored and executed inside the DBMS. It encapsulates a sequence of database operations, allowing code reuse, better performance and improved security. Besides SQL it can contain procedural logic (loops, conditionals, error handling).
Advantages
- Fewer round trips between application and database server: the application issues one call instead of many statements.
- Better performance: user-defined functions are pre-compiled and stored on the server.
- Reusability: write once, use in many applications.
Disadvantages
- Slower software development; requires specialized skills.
- Harder to version-manage and debug.
- May not be portable to other DBMSs (MySQL, SQL Server).
Procedural Languages
PostgreSQL supports SQL, PL/pgSQL and C by default. Others (Perl, Python, JavaScript, Ruby, Java, Tcl) can be added through extensions.
Key Characteristics
- Precompiled: parsed and compiled once, not at each execution.
- Encapsulation: groups related statements into one logical unit.
- Parameterization: accepts input parameters and may return output parameters or result sets.
- Security: users can be granted permission to run a procedure without access to the underlying tables.
- Error handling: built-in exception handling.
PL/pgSQL
PL/pgSQL (Procedural Language/PostgreSQL) is a procedural extension that adds control-flow constructs to SQL.
Features: control structures (IF, CASE, LOOP, WHILE, FOR), error handling with EXCEPTION blocks, dynamic SQL, variables and parameters, seamless integration with SQL.
Basic Syntax
CREATE [OR REPLACE] PROCEDURE procedure_name(parameter_list)
LANGUAGE plpgsql
AS $$
DECLARE
-- variable declarations
BEGIN
-- statements
END;
$$;
CALL procedure_name(arguments);
LANGUAGE plpgsqlspecifies the procedural language.$$delimits the body.- The
DECLAREsection describes all variables.
Control Structures and Error Handling
DO $$
DECLARE
v_count INT;
BEGIN
SELECT COUNT(*) INTO v_count FROM customer;
IF v_count > 100 THEN
RAISE NOTICE 'Large table: %', v_count;
ELSE
RAISE NOTICE 'Small table: %', v_count;
END IF;
FOR i IN 1..3 LOOP
RAISE NOTICE 'Iteration %', i;
END LOOP;
EXCEPTION
WHEN division_by_zero THEN
RAISE NOTICE 'Cannot divide by zero';
END;
$$;
Parameters
| Mode | Purpose |
|---|---|
IN | Pass a value into the procedure (default) |
OUT | Return a value from the procedure |
INOUT | Pass a value in and return a value out |
-- IN
CREATE PROCEDURE add_customer(IN p_first VARCHAR, IN p_last VARCHAR)
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO customer (first_name, last_name) VALUES (p_first, p_last);
END;
$$;
-- OUT
CREATE PROCEDURE get_total(OUT total BIGINT)
LANGUAGE plpgsql AS $$
BEGIN
SELECT COUNT(*) INTO total FROM customer;
END;
$$;
-- INOUT
CREATE PROCEDURE double_it(INOUT x INT)
LANGUAGE plpgsql AS $$
BEGIN
x := x * 2;
END;
$$;
CALL double_it(5); -- returns 10
Functions
Functions encapsulate logic, perform calculations and return results (a scalar, record or table). They accept parameters and can handle errors with PL/pgSQL or SQL.
CREATE OR REPLACE FUNCTION add_numbers(a INT, b INT)
RETURNS INT
LANGUAGE plpgsql AS $$
BEGIN
RETURN a + b;
END;
$$;
SELECT add_numbers(2, 3); -- 5
Stored Procedures vs. Functions
| Feature | Stored Procedures | Functions |
|---|---|---|
| Introduced | PostgreSQL 11 | Early PostgreSQL versions |
| Return value | Not by default (use OUT/INOUT) | Must return a value (scalar, record or table) |
| Transaction control | Supports COMMIT, ROLLBACK, savepoints | Cannot manage transactions |
| Syntax | CREATE PROCEDURE | CREATE FUNCTION |
| Invocation | CALL | Used inside SQL queries or expressions |
| Purpose | Workflows, automation, complex logic | Reusable calculations, data processing |
| Dynamic SQL | Fully supported with EXECUTE | Limited |
| Typical use | ETL processes, data migrations, batch jobs | Data retrieval, calculations |
Choose a procedure when you need transaction control or a multi-step workflow. Choose a function when you need a returned value or want to embed logic in a SQL expression.
Procedure with Multiple Statements and a Transaction
CREATE OR REPLACE PROCEDURE transfer(from_id INT, to_id INT, amount NUMERIC)
LANGUAGE plpgsql AS $$
BEGIN
UPDATE accounts SET balance = balance - amount WHERE id = from_id;
UPDATE accounts SET balance = balance + amount WHERE id = to_id;
COMMIT; -- procedures can control transactions
END;
$$;
CALL transfer(1, 2, 100);
Dynamic SQL
Builds and executes SQL statements at runtime.
EXECUTE format('SELECT COUNT(*) FROM %I', table_name) INTO row_count;
Use format() with %I (identifier) and %L (literal) to avoid SQL injection.
Error Handling
An EXCEPTION block catches runtime errors so they are handled gracefully (e.g., log the error, roll back, or return a message).
BEGIN
-- risky statements
EXCEPTION
WHEN unique_violation THEN
RAISE NOTICE 'Duplicate value';
WHEN OTHERS THEN
RAISE NOTICE 'Error: %', SQLERRM;
END;
Real-World Use Cases
- Data transformation: preprocess data for analytics or reporting (e.g., aggregate sales by region and period).
- Business-logic encapsulation: keep rules in the database for consistency (e.g., automatic salary adjustments based on performance ratings).
Conclusion
Stored procedures and functions move logic next to the data, reducing network traffic and centralizing business rules. Procedures add transaction control; functions return values usable inside queries.
All rights remain with the original author (Algo-holics). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me