PL/pgSQL Function Basics
Write PL/pgSQL functions with parameters, RETURNS TABLE, control flow (IF, LOOP, FOREACH), and exception handling.
What Is PL/pgSQL?
PostgreSQL's built-in procedural language. SQL extended with variables, control flow, exceptions, and the ability to call queries dynamically. Used for stored procedures and trigger functions.
Function Skeleton
A simple function:
CREATE OR REPLACE FUNCTION add(a INT, b INT)
RETURNS INT AS $$
BEGIN
RETURN a + b;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
SELECT add(2, 3); -- 5