1.SQL Functions and PL/pgSQL Functions
A SQL function's body is a single SQL statement (or a short sequence of them) — no branching, no loops, no local variables. A PL/pgSQL function's body is a full procedural block with IF/CASE, loops, variables and exception handling, written in PostgreSQL's own procedural language.
Key features
- A SQL function's body is plain SQL statement(s) — no variables, no control flow
- A PL/pgSQL function's body is a procedural block: DECLARE/BEGIN/END, with IF, LOOP, variables and exceptions
- A simple SQL function can be inlined by the planner into the calling query, which a PL/pgSQL function generally cannot
- Both are created with CREATE FUNCTION; the LANGUAGE clause (sql vs plpgsql) selects which one you get
- PostgreSQL also ships PL/Tcl, PL/Perl and PL/Python as optional procedural languages, and supports custom ones
SQL function vs PL/pgSQL function
- SQL function
- Body is one or more plain SQL statements
- No variables, no control flow
- Can be inlined by the planner into the caller
- PL/pgSQL function
- Body is a procedural block (DECLARE/BEGIN/END)
- IF, CASE, LOOP, variables, exceptions
- Always an opaque call to the planner
Command
-- SQL function: body is one statement
CREATE FUNCTION full_name(first text, last text)
RETURNS text
LANGUAGE sql
AS $$
SELECT first || ' ' || last;
$$;
-- PL/pgSQL function: body is a procedural block
CREATE FUNCTION safe_divide(a numeric, b numeric)
RETURNS numeric
LANGUAGE plpgsql
AS $$
BEGIN
IF b = 0 THEN
RETURN NULL;
END IF;
RETURN a / b;
END;
$$;SQL function = a named SQL statement, inlineable by the planner. PL/pgSQL function = a small program with variables, control flow and exceptions, called as an opaque unit. Pick based on whether the logic needs a decision or a loop, not by default.