🐘 PostgreSQL Intermediate

What are stored procedures and functions in PostgreSQL?

Answer

PostgreSQL supports both functions and stored procedures (since v11). Functions are created with CREATE FUNCTION, return a value (or setof records), and can be called in SQL expressions. They support PL/pgSQL, SQL, Python, and other languages. Stored procedures (CREATE PROCEDURE) can execute transaction commands (COMMIT/ROLLBACK within them) — functions cannot. Functions are called with SELECT func(); procedures with CALL proc(). PL/pgSQL is the most common language: it supports variables, loops, conditionals, cursors, and exception handling. Use LANGUAGE SQL for simple set-returning functions; LANGUAGE plpgsql for procedural logic; LANGUAGE plpython3u for Python logic.