Sub topic 3
Procedures and CALL
This chapter assumes you can write basic SELECT, INSERT, UPDATE, and DELETE statements, and that you can create a function in PostgreSQL. A procedure is a named block of SQL statements that runs them in order. A procedure does not return a result through a query, so you run it with CALL.
CREATE PROCEDURE archive_old_orders(cutoff date)
LANGUAGE sql
AS $$
INSERT INTO orders_archive
SELECT * FROM orders WHERE ordered_at < cutoff;
DELETE FROM orders WHERE ordered_at < cutoff;
$$;
CALL archive_old_orders(date '2025-01-01');This example assumes that orders_archive has the same columns as orders.
Replacing, overloading and dropping functions
CREATE OR REPLACE FUNCTION changes a function body in place. It cannot change the return type, so you must drop the function first to do that.
Overloading means two functions share a name but take different argument types. PostgreSQL chooses the match by argument types. To drop one overload, name its argument types:
DROP FUNCTION add_tax(numeric, numeric);Polymorphic functions
A polymorphic function works with a type chosen at call time. The pseudo-type anyelement stands for any element type.
CREATE FUNCTION make_array(anyelement, anyelement)
RETURNS anyarray
LANGUAGE sql
IMMUTABLE
AS $$
SELECT ARRAY[$1, $2];
$$;
SELECT make_array(1, 2), make_array('a'::text, 'b');How the planner inlines SQL functions
The planner is PostgreSQL's query optimizer. For a simple scalar SQL function, the planner can replace the function call with the function's expression. The optimizer then sees the whole query and can optimize it. Functions with SECURITY DEFINER or a SET clause are not inlined. Use EXPLAIN to confirm what the planner does with your function.
SECURITY DEFINER done safely
SECURITY DEFINER runs a function with its owner's privileges. Set search_path so callers cannot redirect table names to their own objects. Then revoke the default EXECUTE privilege from PUBLIC and grant it to specific roles.
CREATE FUNCTION get_balance(p_account int)
RETURNS numeric
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = pg_catalog, public
AS $$
SELECT balance FROM accounts WHERE id = p_account;
$$;
REVOKE EXECUTE ON FUNCTION get_balance(int) FROM PUBLIC;COST, ROWS and parallel safety
COST gives the planner an estimated cost per call. ROWS gives an estimated row count for set-returning functions. PARALLEL states whether the function can run in parallel workers: PARALLEL SAFE, RESTRICTED, or UNSAFE. Wrong estimates can lead the planner to pick a poor plan.
When to use SQL and when to use PL/pgSQL
Use a SQL function for one query or expression. Use PL/pgSQL when you need variables, loops, conditionals, or exception handling.
Exercise
Why does a procedure run with CALL instead of SELECT?
Show answer
A procedure returns no result through a query, so PostgreSQL runs it as a statement with CALL.