Sub topic 3
Raising and handling errors
This chapter assumes you can write basic SQL, know PostgreSQL tables and data types, and understand variables and conditionals. It covers error handling, function settings, procedures, dynamic SQL, triggers, and performance.
Raising and handling errors
RAISE EXCEPTION stops the function and reports a message to the caller. SELECT ... INTO STRICT fails unless exactly one row matches, and an EXCEPTION block catches that failure so you can report it clearly.
CREATE FUNCTION get_customer_email(p_id integer)
RETURNS text
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_email text;
BEGIN
SELECT email INTO STRICT v_email FROM customers WHERE id = p_id;
RETURN v_email;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE EXCEPTION 'customer % not found', p_id;
END;
$$;Volatility, STRICT, and SECURITY DEFINER
VOLATILE(the default) lets the planner assume nothing about repeated calls.STABLEmeans the result stays the same within one statement.IMMUTABLEmeans the result depends only on the arguments.STRICTmakes the function return NULL without running when any argument is NULL.SECURITY DEFINERruns the function with the owner's privileges. Pair it withSET search_pathso callers cannot redirect table lookups.
Stored procedures, CALL, and transaction control
A procedure is created with CREATE PROCEDURE and run with CALL. Unlike a function, a procedure can use COMMIT and ROLLBACK inside its body. This works only when the procedure is called directly, not inside an explicit transaction block.
Dynamic SQL with EXECUTE and format()
Use EXECUTE when the table or column name is known only at run time. Quote identifiers with %I, and pass values with USING so they are never pasted into the SQL text.
CREATE FUNCTION count_where(p_table text, p_column text, p_value text)
RETURNS bigint
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_count bigint;
BEGIN
EXECUTE format('SELECT count(*) FROM %I WHERE %I = $1', p_table, p_column)
INTO v_count
USING p_value;
RETURN v_count;
END;
$$;Writing trigger functions
A trigger function returns type trigger. In a row trigger, NEW holds the incoming row, OLD holds the previous row, and TG_OP tells you whether the event was INSERT, UPDATE, or DELETE.
CREATE FUNCTION set_updated_at()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END;
$$;
CREATE TRIGGER trg_orders_updated_at
BEFORE UPDATE ON orders
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();Performance, testing, and maintenance
Prefer one set-based query over a row-by-row loop. Check the SQL inside a function with EXPLAIN ANALYZE. Keep function definitions in version control, and test each function after every change.
Exercise
The function getcustomeremail raises an error when no customer matches. Why does the function need an EXCEPTION block for this case when a plain SELECT INTO would not raise a clear message?
Show answer
SELECT INTO STRICT raises the built-in NODATAFOUND error. The EXCEPTION block catches it and replaces it with a message that names the missing customer ID.