Sub topic 9
Raising and Handling Errors in PL/pgSQL
Assume you know basic SQL, PostgreSQL data types, and programming ideas such as variables, conditions, and loops. This chapter focuses on errors inside PL/pgSQL functions. The same error statements also work in procedures.
Raising an error deliberately
Use RAISE to report information or stop execution. Its severity controls what PostgreSQL does:
RAISE NOTICEreports normal progress.RAISE WARNINGreports a problem but continues.RAISE EXCEPTIONstops the current block and returns an error to the caller.
A raised exception rolls back the statements executed in the current transaction unless the caller catches it at another level.
CREATE FUNCTION validate_order_total(p_total numeric)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
IF p_total IS NULL OR p_total <= 0 THEN
RAISE EXCEPTION USING
ERRCODE = '22023',
MESSAGE = 'order total must be positive',
DETAIL = format('Received total: %s', p_total),
HINT = 'Pass a value greater than zero.';
END IF;
RAISE NOTICE 'Order total % is valid', p_total;
END;
$$;
SELECT validate_order_total(125.50);
-- SELECT validate_order_total(0); -- raises an errorERRCODE is a five-character SQLSTATE code. Code 22023 means an invalid parameter value. You can also use the condition name invalid_parameter_value.
Catching errors with an exception block
An EXCEPTION section handles errors raised by the statements in its BEGIN section. PostgreSQL checks the handlers from top to bottom and runs the first matching handler.
CREATE FUNCTION get_order_total(p_order_id integer)
RETURNS numeric
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_total numeric;
BEGIN
SELECT total
INTO STRICT v_total
FROM orders
WHERE id = p_order_id;
RETURN v_total;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE EXCEPTION 'order % was not found', p_order_id
USING ERRCODE = 'P0001';
WHEN TOO_MANY_ROWS THEN
RAISE EXCEPTION 'order lookup for % returned multiple rows', p_order_id
USING ERRCODE = 'P0001';
END;
$$;INTO STRICT requires exactly one row. It raises NO_DATA_FOUND when no row matches and TOO_MANY_ROWS when more than one row matches. Without STRICT, no matching row assigns NULL, which can hide a data error.
An exception handler creates a protected subtransaction. Changes made in the block before the error are rolled back, but changes made before entering the block remain. Keep handlers narrow because exception blocks add overhead.
SQLSTATE and diagnostics
Use named conditions such as unique_violation when they make the code clearer. Use SQLSTATE when you need an exact, portable error category.
WHEN OTHERS catches most errors, but it should not silently ignore them. Capture details with GET STACKED DIAGNOSTICS, log or add context, and re-raise the original error.
EXCEPTION
WHEN OTHERS THEN
DECLARE
v_state text;
v_message text;
BEGIN
GET STACKED DIAGNOSTICS
v_state = RETURNED_SQLSTATE,
v_message = MESSAGE_TEXT;
RAISE WARNING 'Order operation failed (%): %', v_state, v_message;
RAISE;
END;The final RAISE preserves the original SQLSTATE and error context. This is safer than returning a success value after a failure.
Exercise
Why is SELECT ... INTO STRICT useful when a function expects one customer row?
Show answer
It turns both “no row” and “multiple rows” into explicit errors, preventing the function from silently using NULL or an arbitrary result.