Skip to content
ImagineWorld

Functions and Stored Procedures

node_idnode-book_ai-ready-postgresql-18_chapter-06-functions-and-stored-procedures
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleFunctions and Stored Procedures
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 6 — Functions and Stored Procedures

Section titled “Chapter 6 — Functions and Stored Procedures”

Functions and procedures enable developers to package frequently used SQL statements and manage their execution using IF / THEN / LOOP and other control statements. Functions and procedures modularize and encapsulate business logic, making it easy to bring the logic to the data, rather than moving all the data from the database to the applications first. This minimizes the roundtrips between the application and data, significantly improving transaction performance and latency.

Last, but not least, functions and stored procedures are important security mechanisms that can provide secure, selective access to data, without exposing the tables themselves.

Functions have been supported since Postgres95, before it became PostgreSQL. Procedures were added in PostgreSQL version 11.

In this chapter, we will discuss the differences between functions and procedures, both in general and specifically in PostgreSQL. We will also examine functions and procedures that utilize SQL exclusively, before exploring the use of procedural languages that support more complex business logic. PostgreSQL supports many procedural languages, and we have selected PL/PGSQL, PostgreSQL’s native procedural language, and PL/Python, the popular language for AI and data analytics, as two representative examples.

The chapter reviews several PostgreSQL extensions that enhance developer productivity, such as plpgsql_check, and help circumvent some of the limitations of the transactional model, including pg_background.

A systematic comparison table of PL/pgSQL and PL/Python helps the developer choose the right tool for the job at hand.

This chapter covers the following topics:

  • Understanding functions and stored procedures in PostgreSQL
  • Differences between functions and procedures
  • Writing SQL-based functions and procedures
  • Function volatility and performance considerations
  • Using PL/pgSQL and PL/Python for advanced logic
  • Triggers, transaction handling, and developer best practices

All examples in the chapter are available in the GitHub repo under psql_scripts / sample_scripts / chapter_6.sql.

Functions or Procedures? What’s the difference?

Section titled “Functions or Procedures? What’s the difference?”

The literature differentiates between different programming styles, such as object-oriented, event-oriented, function-oriented, and procedure-oriented. In PostgreSQL, we use mostly function-oriented or procedure-oriented approaches. The PostgreSQL LISTEN command also provides a tool to support event-based approaches.

Often, function-oriented approaches are described as deterministic, meaning they return the same value for the same inputs, avoiding side effects and not changing global data structures. Procedural approaches focus on changing global variables or data structures, and not on return values.

Functions in PostgreSQL have return values, but they can also modify the environment (that is, make changes to the database state), and their return value is not only determined by the input parameters, except for IMMUTABLE functions, which do not access the database and determine the return result only based on the input parameters.

Here are the key differences:

  • Functions can be called within SQL queries, and their results can be leveraged in the query.
  • Procedures are invoked using CALL, and they do not return results, but they can modify some of the parameters used to invoke the stored procedure.
  • Functions can return scalar values or result sets. Procedures can return data via OUT or INOUT parameters, which are not limited to scalar data types.
  • Functions cannot have transaction control statements, such as COMMIT, ROLLBACK, or transaction control. Functions participate in the transaction context of the caller.
  • Procedures can manage transactions using COMMIT and ROLLBACK; in PL/pgSQL, they can also use exception blocks to create subtransactions.
  • Functions (and procedures) can be overloaded, which means that the same routine name can have different parameter lists and execute different statement sequences depending on the parameters provided

We will now dive into the details of how to construct functions and procedures, and then guide the developer on when to use either one.

Procedures and functions can consist of sequences of SQL statements without flow control (IF / THEN / LOOP /etc.). This basic level of procedure and function may feel “stripped down,” but it is still beneficial as it packages sequences of commands, defines modules, encapsulates functionality, and can be used to provide secure and controlled access to data.

In the following sections, we will review the core capabilities of SQL-only procedures and functions. These capabilities remain relevant when we add procedural flow control through PL/pgSQL and PL/Python.

The basic structure of procedures and functions is very similar, as shown in Table 6.1 for a subset of the key building blocks:

  • Function or procedure name: Remember the recommended coding convention from Chapter 3*,* A Sample E-Commerce Application (procedure names start with p_, function names start with f_).
  • Parameter declaration: Parameters can be IN, OUT, INOUT, or VARIADIC, and they can have default values. The recommended coding convention uses p_ for parameter names.
  • The volatility classification is optional and applicable to functions only. The default is VOLATILE. More details about how and why the right classification matters follow.
  • The RETURNS clause is only defined for functions. Keep in mind that a function can return a scalar value (e.g., an INTEGER, a RECORD), or data of the type of any table defined in the database.
  • AS $$ … $$ defines the string that constitutes the SQL body of the procedure or function. There are other ways (for example, using single quotes), but the approach is the most common (and tagged dollar-quoting, such as $ func $...$ func $, is often used when the body itself contains $$).
  • The declaration section is optional. Using DECLARE, we can define variables with datatypes and default values for use within the function or procedure. We recommend using v_ as a prefix for variable names.
  • BEGIN and END delineate the sequence of statements, but these should not be confused with the similarly named SQL commands for initiating and ending a SQL transaction.
  • Language indicator: Functions and procedures that do not use any procedural flow control statements, such as IF / THEN / LOOP, can be declared in the SQL language. Once they use procedural controls, it becomes essential to identify the language as plpgsql, plpython3u, pltcl, and so on.

The preceding list focuses on the key building blocks. It is essential to consult the PostgreSQL documentation to understand the full breadth of PostgreSQL capabilities.

FunctionProcedure
CREATE FUNCTION <function name> ( IN/OUT p_parameter1 <DATATYPE> DEFAULT = <x>; …) IMMUTABLE/STABLE/VOLATILE RETURNS (<DATATYPE>) AS $$ DECLARE v_variable1 <DATATYPE>; …; BEGIN <STATEMENT>; <STATEMENT>; END $$ LANGUAGE <language>;CREATE PROCEDURE <function name> ( IN/OUT p_parameter1 <DATATYPE> DEFAULT = <x>; …) AS $$ DECLARE v_variable1 <DATATYPE>; …; BEGIN <STATEMENT>; <STATEMENT>; END $$ LANGUAGE <language>;

Table 6.1: Key building blocks of the PostgreSQL function and procedure definitions

Functions can be labeled with three different volatility definitions: immutable, stable, and volatile. This label is optional, and if not provided, PostgreSQL defaults to volatile. However, the correct labeling can have a significant performance impact.

  • Immutable: The function always returns the same value for the same inputs. Immutable functions do not interact with the database. This gives the optimizer a significant opportunity to select an optimal execution strategy.
  • Stable: A stable function cannot modify the database, but it can use the SELECT statement to query the database. Given the same database state, it will always return the same results.
  • Volatile: A function labeled as volatile can query and update the database, and the optimizer cannot make any assumptions about possible optimizations. This is the default.

One key reason for the potential performance impact of choosing the correct volatility classification is that immutable and stable functions leverage the database snapshot that was acquired by the calling query. In contrast, volatile functions acquire a new snapshot every time they are invoked.

Procedural languages enable us to add flow control to functions and procedures, facilitating effective transaction management within these procedures. Keep in mind that PostgreSQL functions cannot control transactions; they run entirely within the caller’s current transaction context. Only procedures can define transaction boundaries using COMMIT and ROLLBACK. Refer to the Transactions and s ubtransactions section for details on transaction management using PL/pgSQL.

PostgreSQL supports a multitude of procedural languages. Some of the procedural languages are included with most PostgreSQL distributions and can easily be added through the ADD EXTENSION command:

  • PL/pgSQL: the original and default procedural language for PostgreSQL
  • PL/Tcl: a powerful string processing language
  • PL/Perl: uses the Perl programming language to write stored procedures and functions
  • PL/Python3u: gives developers access to Python 3 to write stored procedures and perform AI and data science operations

For a complete list of all available procedural languages, consult the corresponding page on the PostgreSQL.org wiki.

Trusted vs. Untrusted procedural languages

Section titled “Trusted vs. Untrusted procedural languages”

Some PostgreSQL procedural languages, such as PL/Python3u, are only available as untrusted languages. Others, such as Perl, are available in trusted and untrusted configurations. A language is classified as “trusted” when it runs within the controls of the database, and the database security mechanisms can restrict the user’s access to the file system or the WWW. An untrusted language, such as PL/Python3u, allows anybody with access to it to create and run code that has the same privileges as a superuser. That is why you must be a superuser in PostgreSQL to define functions or procedures in any untrusted language.

In the following two sections, we provide a detailed examination of PL/pgSQL and PL/Python3u.

PL/pgSQL: PostgreSQL’s native procedural language

Section titled “PL/pgSQL: PostgreSQL’s native procedural language”

PL/pgSQL first appeared in PostgreSQL Version 6.4, released in 1998. It is closely aligned, syntactically and semantically, with standard SQL. It adds many procedural aspects, such as IF/THEN/ELSE, various loop constructs to iterate through query results, arrays, or simple integer counts, and transaction control statements, including BEGIN, COMMIT, ROLLBACK, and SAVEPOINT.

The basic structure of procedures and functions that leverage PL/pgSQL is the same as shown in Table 6.1.

For functions, PL/pgSQL adds the explicit definition of the return value using the RETURN clause (a SQL-only function that does not leverage PL/pgSQL returns the value of the last SELECT statement in the statement sequence).

The RETURN clause also terminates the function’s execution.

For procedures, PL/pgSQL allows explicit transaction control using the BEGIN statement, commits transactions with COMMIT, rolls back the work since the current transaction started with ROLLBACK, and defines a SAVEPOINT.

For functions and procedures, PL/pgSQL provides a variety of flow control structures.

  • IF / THEN / ELSE / ELSE IF / END IF provide the simple if-then -else logic that we are familiar with from most programming languages. The following is an example of an anonymous DO block:
    DO
    $$
    DECLARE x INTEGER := 4;
    BEGIN
    IF x = 1 OR x = 2 THEN
    RAISE NOTICE 'The value is either 1 or 2';
    ELSEIF x = 3 THEN
    RAISE NOTICE 'The value is 3';
    ELSE
    RAISE NOTICE 'The value is neither 1, 2, nor 3';
    END IF;
    END
    $$;
  • CASE allows us to switch to a branch of code. In PostgreSQL, CASE comes in two flavors:
    • Simple CASE, where a search expression, which is evaluated once, is compared (using equal) to expressions in the branching condition
      • Searched CASE, where every branch has a separate expression that is evaluated to identify the next code branch In both cases, the first matching branch is selected, and execution will continue after the END CASE statement (unless EXIT, RETURN, or an exception is encountered). Here’s a simple CASE statement:
    DO
    $$
    DECLARE x INTEGER := 4;
    BEGIN
    CASE x
    WHEN 1, 2 THEN
    RAISE NOTICE 'The value is either 1 or 2';
    WHEN 3 THEN
    RAISE NOTICE 'The value is 3';
    ELSE
    RAISE NOTICE 'The value is neither 1, 2, nor 3';
    END CASE;
    END
    $$;
    Here’s a searched CASE statement:
    DO
    $$
    DECLARE x INTEGER := 4;
    BEGIN
    CASE
    WHEN x IN (1, 2) THEN
    RAISE NOTICE 'The value is either 1 or 2';
    WHEN x = 3 THEN
    RAISE NOTICE 'The value is 3';
    ELSE
    RAISE NOTICE 'The value is neither 1, 2, nor 3';
    END CASE;
    END
    $$;
  • LOOP runs the statement block repeatedly until the EXIT statement is encountered
    DO
    $$
    DECLARE
    v_max INTEGER := 4;
    v_ctr INTEGER :=1;
    BEGIN
    LOOP
    RAISE NOTICE 'Iteration # %', v_ctr;
    IF v_ctr >= v_max THEN
    EXIT;
    ELSE
    v_ctr := v_ctr +1;
    END IF;
    END LOOP;
    END
    $$;
  • A WHILE LOOP performs the same task, but it checks the condition as part of the initial statement. The preceding loop would start with WHILE v_ctr < v_max LOOP.
  • FOR LOOPS come in multiple shapes:
    1. FOR < name > IN < start > … < end > LOOP iterates over an integer range 2. FOR iterates through an array 3. FOR iterates through the records resulting from a select query

Let’s explore the various forms of the LOOP statement more thoroughly.

The simplest form of the FOR LOOP iterates over an integer range. The iteration variable is implicitly created as an INTEGER:

DO
$$
DECLARE
v_max INTEGER := 4;
BEGIN
FOR v_ctr IN 1.. v_max LOOP
RAISE NOTICE 'Iteration # %', v_ctr;
END LOOP;
END
$$;

The FOREACH iterates through an array:

DO
$$
DECLARE
v_array INTEGER[]:= '{1,2,3,4}';
v_i INTEGER;
BEGIN
FOREACH v_i IN ARRAY v_array LOOP
RAISE NOTICE 'Iteration # %', v_i;
END LOOP;
END
$$;

The SLICE statement makes it easy to work with multi-dimensional arrays by giving us access to one dimension (=slice) of the array at a time:

DO
$$
DECLARE
v_array INTEGER[][]:= '{{1,2},{2,3},{3,5},{4,7}}';
v_i INTEGER[];
BEGIN
FOREACH v_i SLICE 1 IN ARRAY v_array LOOP
RAISE NOTICE 'Prime number # % = %', v_i[1], v_i[2];
END LOOP;
END
$$;

FOR … IN makes it easy to iterate through record sets. In this example, we search for all products with prices between 0.70and0.70 and 0.99 and round them up to the nearest dollar, $0.99. Note that we are utilizing the PostgreSQL 18 feature that allows returning both old and new values from queries using the aliases OLD and NEW.

DO $$
DECLARE
v_product_variant_price_record RECORD;
v_new_price NUMERIC;
v_old_price NUMERIC;
BEGIN
-- find all the current product prices that are close to the round num-ber
-- and adjust them to 0.99
FOR v_product_variant_price_record
IN
(SELECT *
FROM product_variant_price
WHERE
current = TRUE
AND (price - TRUNC(price))> .70)
LOOP
UPDATE product_variant_price
SET price = TRUNC (price) + 0.99
WHERE product_variant_price.id =
v_product_variant_price_record.id
-- use new PostgreSQL 18 capability to return old and new
RETURNING NEW.price, OLD.price INTO v_new_price, v_old_price;
RAISE NOTICE 'Changed price for id % from % to %',
v_product_variant_price_record.id, v_old_price, v_new_price;
END LOOP;
END;
$$;

PostgreSQL provides versatile flow control statements. We recommend that developers consult the PostgreSQL documentation about control structures to understand the full extent of the PL/pgSQL capabilities.

Diagnostics to understand the most recent query

Section titled “Diagnostics to understand the most recent query”

PostgreSQL provides a set of variables that report on the last executed query in a session.

  • FOUND tells us whether the last query returned any records (SELECT) or changed any records (INSERT, UPDATE, DELETE). If FOUND is false, then the query did not return any results or modify any records.
  • GET DIAGNOSTICS provides information about the exact row count, the OID of the current function, and the context of the current execution.

The example illustrates the power of GET DIAGNOSTICS.

DO $$
DECLARE
v_call_stack TEXT;
v_row_count INTEGER;
v_OID OID;
BEGIN
PERFORM * FROM product;
GET DIAGNOSTICS v_row_count = ROW_COUNT;
GET DIAGNOSTICS v_OID = PG_ROUTINE_OID;
GET DIAGNOSTICS v_call_stack = PG_CONTEXT;
RAISE NOTICE 'Routine OID %', v_OID;
RAISE NOTICE 'Call stack: %', v_call_stack;
IF FOUND THEN
RAISE NOTICE 'Query successful. Found % rows', v_row_count;
ELSE
RAISE NOTICE 'Nothing found';
END IF;
END;
$$;
NOTICE: Routine OID 0
NOTICE: Call stack: PL/pgSQL function inline_code_block line 10 at GET DIAGNOSTICS
NOTICE: Query successful. Found 31 rows

Do not confuse DIAGNOSTICS, which provides information about the current state of execution, with the STACKED DIAGNOSTICS command, which offers detailed information during an error. The following section will include information about Stacked Diagnostics, an essential tool for handling exceptions.

Exception handling and Stacked Diagnostics

Section titled “Exception handling and Stacked Diagnostics”

Exceptions can result from errors that PostgreSQL detects or from RAISE statements that the developer inserts to handle exceptional situations.

This statement results in an error as it violates a check constraint on price:

UPDATE product_variant_price SET price = -0.99 WHERE id = 1;
A simple handler catches the error and raises a notice.
DO $$
BEGIN
UPDATE product_variant_price SET price = -0.99 WHERE id = 1;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'Update failed';
END;
$$;

A more sophisticated handler is added for the specific problem of violating that check constraint:

DO $$
DECLARE
v_MESSAGE_TEXT TEXT;
v_CONSTRAINT_NAME TEXT;
v_TABLE_NAME TEXT;
BEGIN
-- this will fail as table constraint requires prices > 0
UPDATE product_variant_price SET price = '-0.99' WHERE id = 1;
EXCEPTION
WHEN check_violation THEN
RAISE NOTICE 'Violated check constraint; Details below';
GET STACKED DIAGNOSTICS
v_CONSTRAINT_NAME = CONSTRAINT_NAME,
v_MESSAGE_TEXT = MESSAGE_TEXT,
v_TABLE_NAME = TABLE_NAME;
RAISE NOTICE 'CONSTRAINT_NAME %', v_CONSTRAINT_NAME;
RAISE NOTICE 'MESSAGE_TEXT %',v_MESSAGE_TEXT;
RAISE NOTICE 'TABLE_NAME %', v_TABLE_NAME;
END;
$$;
NOTICE: Violated check constraint; Details below
NOTICE: CONSTRAINT_NAME product_variant_price_price_check
NOTICE: MESSAGE_TEXT new row for relation "product_variant_price" violates check constraint "product_variant_price_price_check"
NOTICE: TABLE_NAME product_variant_price

In the preceding example, replacing '-0.99' with 'test' reveals that the new error type does not match check_violation, resulting in the exception not being handled.

GET STACKED DIAGNOSTICS provides a wealth of information that the developer can use for potent and specific handling of exception conditions.

The developer can also raise custom exceptions using the RAISE EXCEPTION command, specifying a message, hint, detail, error code, and other parameters.

DO $$
BEGIN
UPDATE product_variant_price SET price = 0.01 WHERE id =1;
RAISE check_violation USING MESSAGE = 'Price too low';
END $$;
ERROR: Price too low
CONTEXT: PL/pgSQL function inline_code_block line 4 at RAISE

In this section, we reviewed the most critical control flow constructs for PL/pgSQL. The following section will explore a somewhat separate construct: triggers. They are not part of a general procedural flow; instead, they are activated when specific events occur or data changes happen.

Triggers: Reacting to data changes and events

Section titled “Triggers: Reacting to data changes and events”

Triggers in PostgreSQL react to data changes in tables or events at the session or server level. Event triggers are currently limited to Data Definition Language (DDL) execution, such as CREATE, ALTER, or DROP statements, and login events (introduced in PostgreSQL version 17). Data triggers react to statements (statement-level triggers) that impact tables, such as INSERT, UPDATE, and DELETE, and changes at the row level (row-level triggers).

Data triggers are more popular than event triggers and are an essential tool for managing data.

To create a new data-driven trigger, we first define the trigger function. Trigger functions always returns trigger (for data triggers) or event_trigger (for event triggers), and they have access to the following:

  • NEW record (for INSERT and UPDATE row-level triggers)
  • OLD record (for UPDATE and DELETE row-level triggers)
  • TG_NAME (trigger name)
  • TG_WHEN (whether it is a BEFORE, AFTER, or INSTEAD OF trigger)
  • TG_LEVEL (ROW or STATEMENT)
  • TG_OP (operation: INSERT, UPDATE, DELETE, or TRUNCATE)
  • Other trigger context variables

In our example, we track who made a change to the product_variant_inventory table, including the change maker, the change time, and a JSONB document of the prior values. This will include the complete history of changes as a nested JSONB record. This trigger-based approach is most useful when auditing must be enforced consistently across many code paths; if an application can reliably record these fields in the original UPDATE / INSERT statement, that approach is typically simpler and faster.

As the current definition of the inventory table does not include these columns, we first add them:

ALTER TABLE product_variant_inventory
ADD COLUMN last_update_timestamp TIMESTAMP,
ADD COLUMN last_update_user TEXT,
ADD COLUMN prior_value JSONB;

Then we define the trigger function:

CREATE OR REPLACE FUNCTION tr_inventory_last_update() RETURNS TRIGGER
AS
$$
BEGIN
NEW.last_update_timestamp = NOW();
NEW.last_update_user = CURRENT_USER;
NEW.prior_value = TO_JSONB (OLD);
RETURN NEW; -- returns the new row
END
$$ LANGUAGE PLPGSQL;

Then we add the trigger function to the specific operation on the table. In this case, the function gets triggered as a row-level statement before an update or an insert.

-- adding the trigger to the table as a BEFORE trigger for INSERT and UPDATE
CREATE OR REPLACE TRIGGER tr_track_last_update_inventory
BEFORE INSERT OR UPDATE
ON product_variant_inventory
FOR EACH ROW EXECUTE FUNCTION tr_inventory_last_update();

This output shows the inventory table after we changed the quantity for product variant 1 twice, from the original value of 94 to 93, and then to 90.

SELECT
product_variant_id id,
qty,
DATE(last_update_timestamp) date,
last_update_user user,
JSONB_PRETTY (prior_value) AS prior_value
FROM product_variant_inventory WHERE product_variant_id = 1;
id | qty | date | user | prior_value
----+-----+------------+----------+--------------------------------------
1 | 90 | 2025-08-29 | postgres | {
| | | | "qty": 93, +
| | | | "prior_value": { +
| | | | "qty": 94, +
| | | | "prior_value": null, +
| | | | "last_update_user": null, +
| | | | "product_variant_id": 1, +
| | | | "last_update_timestamp": null
| | | | },
| | | |"last_update_user": "postgres",
| | | |"product_variant_id": 1,
| | | |"last_update_timestamp": "2025-08-29".
| | | | }

Triggers are often used to track changes in tables or handle restrictions not defined as part of check constraints – for example, a minimum price that does not violate a database constraint but does not align with current business practices. They can also be used to create audits, as shown, history tables, or to define other side effects.

The previous sections explained how to define control structures, loops, and conditions in procedural code in PostgreSQL. We also discussed trigger functions that are activated by data changes and are not called as part of other functions or procedures.

This section focuses on managing complex transactions in PL/pgSQL. BEGIN / COMMIT / ROLLBACK are the basic elements introduced in Chapter 5; now, we will explore subtransactions in more detail.

Transaction blocks can be partially nested using subtransactions, allowing developers to undo parts of a complex transaction selectively. In PL/pgSQL, subtransactions are typically created implicitly using BEGIN … EXCEPTION … END blocks (rather than SAVEPOINT statements). This example contains a subtransaction that commits a single sales line and its inventory. In the event of an exception, only that line is rolled back, and the rest of the transaction is completed.

CREATE OR REPLACE FUNCTION sf_add_lines_to_sales_order (
p_sales_transaction_id TEXT, -- sales transaction
p_line_info NUMERIC[][][] --- order lines with product, qty, and price
)
RETURNS INTEGER[][] --- product and quantities that were committed suc-cessfully
AS
$$
DECLARE
v_products_ordered INTEGER[][]; -- result array of all successful lines
v_pv_id INTEGER; -- variable for product_variant_id
v_qty INTEGER; -- variable for qty
v_price NUMERIC; -- variable for price
BEGIN
-- iterate through all the lines and commit the inventory
FOR v_i IN 1.. ARRAY_LENGTH(p_line_info, 1) LOOP
BEGIN -- start a new subtransaction for each line of the order
v_pv_id := p_line_info[v_i][1];
v_qty := p_line_info[v_i][2];
v_price := p_line_info[v_i][3];
-- add the sales transaction line
INSERT INTO sales_transaction_line
(sales_transaction_id, product_variant_id, qty, price_at_sale)
VALUES
(p_sales_transaction_id, v_pv_id, v_qty, v_price);
-- commit the inventory
UPDATE product_variant_inventory
SET qty = qty - v_qty
WHERE product_variant_id = v_pv_id;
RAISE NOTICE
'Success with order % for % units. Sufficient inventory on hand',
v_pv_id, v_qty;
-- add this successful line to the return result
v_products_ordered :=
v_products_ordered || ARRAY[[v_pv_id, v_qty]];
-- In case of an exception in this subtransaction,
-- the latest line will be rolled back
-- all other lines will be committed, unless
-- there is another error that is not handled
EXCEPTION -- handle exceptions that pertain to
-- this line of the order
WHEN check_violation THEN
RAISE NOTICE
'Failure with % for % units. Out of inventory',
p_line_info[v_i][1], p_line_info[v_i][2];
END;
END LOOP;
RETURN v_products_ordered;
END
$$ LANGUAGE PLPGSQL;

When this function is invoked, all the lines with sufficient on-hand inventory will be committed, and the others will be rolled back. The function returns an array of the IDs and quantities that were successfully committed.

...=# SELECT sf_add_lines_to_sales_order AS committed_lines
...-# FROM sf_add_lines_to_sales_order(
... (# 'east_5316',
... (# '{{1,1,29.11}, {7,1,15}, {8,1, 32}, {18,3, 58}, {19,1, 5.23}}');
NOTICE: Success with order 1 for 1 units. Sufficient inventory on hand
NOTICE: Success with order 7 for 1 units. Sufficient inventory on hand
NOTICE: Success with order 8 for 1 units. Sufficient inventory on hand
NOTICE: Failure with 18 for 3 units. Out of inventory
NOTICE: Success with order 19 for 1 units. Sufficient inventory on hand
committed_lines
----------------------------
{{1,1},{7,1},{8,1},{19,1}}

pg_background: Breaking out of the transaction constraints

Section titled “pg_background: Breaking out of the transaction constraints”

Let’s assume we want to create a table that includes all inventory requests, both those that were fulfilled and those that were not. While the preceding function identifies shortages and skips sales lines without inventory, it cannot track failed inventory requests in a table. Why? Because inserts into such an inventory request table occur within the transaction that created an exception and rolls back. Any inserts into the inventory request table are also rolled back.

To solve this problem, we need to spawn a separate, independent transaction that does not run within the original transactional context of the calling function, sf_add_lines_to_sales_order. In PostgreSQL, we utilize the pg_background extension. This allows us to execute procedures and functions in the background, in a separate process, and outside of the context of the transaction that spawned the new command.

We will illustrate this using the sf_add_lines_to_sales_order function, previously described. The record_inventory_request procedure is called through the pg_background framework and adds lines to the inventory_request table – even for failed transactions!

CREATE EXTENSION pg_background;
CREATE TABLE inventory_request (
time TIMESTAMP,
product_variant_id INTEGER,
sales_transaction_id TEXT,
qty INTEGER);
CREATE OR REPLACE PROCEDURE record_inventory_request (
p_product_variant_id INTEGER,
p_sales_transaction_id TEXT,
p_qty INTEGER)
AS
$$
BEGIN
INSERT INTO inventory_request
(time, product_variant_id,sales_transaction_id, qty)
VALUES (CLOCK_TIMESTAMP(), p_product_variant_id,p_sales_transaction_id, p_qty);
END
$$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION sf_add_lines_to_sales_order (
p_sales_transaction_id TEXT, -- sales transaction
p_line_info NUMERIC[][][]) --- order lines with product, qty, and price
RETURNS INTEGER[][] --- product and quantities that were committed successfully
AS
$$
DECLARE
v_products_ordered INTEGER[][] := ARRAY[]::INTEGER[][]; -- result array of all successful lines
v_i INTEGER;
v_pv_id INTEGER;
v_qty INTEGER;
v_price NUMERIC;
v_background_command TEXT; -- command to run in the background
v_bg_worker_pid INTEGER; -- Variable to hold the background worker's PID
v_bg_result TEXT; -- Variable to hold the result from the background worker
BEGIN
-- iterate through all the lines and commit the inventory
FOR v_i IN 1.. ARRAY_LENGTH(p_line_info, 1) LOOP
BEGIN -- start a new subtransaction for each line of the order
v_pv_id := p_line_info[v_i][1];
v_qty := p_line_info[v_i][2];
v_price := p_line_info[v_i][3];
-- Use pg_background to record the inventory request in the background
-- 1) Build the command string for the background worker
v_background_command := format(
'CALL record_inventory_request(%L, %L, %L)',
v_pv_id,
p_sales_transaction_id,
v_qty
);
-- 2) Launch the worker and capture its PID
v_bg_worker_pid := pg_background_launch(v_background_command);
-- 3) Capture any results (including errors) and detach the background process
SELECT result INTO v_bg_result FROM pg_background_result(v_bg_worker_pid) AS (result TEXT);
-- Print the result from the background worker if level is set to DEBUG
RAISE DEBUG 'Background worker result: %', v_bg_result;
-- 4) Now we can proceed with the main transaction
-- 4.a) add the sales transaction line
INSERT INTO sales_transaction_line
(sales_transaction_id, product_variant_id, qty, price_at_sale)
VALUES
(p_sales_transaction_id,v_pv_id,v_qty,v_price);
-- 4.b) commit the inventory
UPDATE product_variant_inventory SET qty = qty - v_qty
WHERE product_variant_id = v_pv_id;
RAISE NOTICE 'Success with order % for % units. Sufficient inventory on hand',
v_pv_id, v_qty;
-- add this successful line to the return result
v_products_ordered := v_products_ordered || ARRAY[[v_pv_id, v_qty]];
-- In case of an exception in this subtransaction,
-- the latest line will be rolled back
-- all other lines will be committed, unless
-- there is another error that is not handled
EXCEPTION -- handle exceptions that pertain to this line of the order
WHEN check_violation THEN
RAISE NOTICE 'Failure with % for % units. Out of inventory',
v_pv_id, v_qty;
END;
END LOOP;
RETURN v_products_ordered;
END $$ LANGUAGE PLPGSQL;

When we call this function, after having set the inventory to 1 for all product variants involved, we get the following result:

east_ecommerce_data=# SELECT sf_add_lines_to_sales_order AS committed_lines
east_ecommerce_data-# FROM sf_add_lines_to_sales_order(
east_ecommerce_data(# 'east_5316',
east_ecommerce_data(# '{{1,1,29.11}, {7,1,15}, {8,1, 32}, {18,3, 58}, {19,1, 5.23}}');
NOTICE: Success with order 1 for 1 units. Sufficient inventory on hand
NOTICE: Success with order 7 for 1 units. Sufficient inventory on hand
NOTICE: Success with order 8 for 1 units. Sufficient inventory on hand
NOTICE: Failure with 18 for 3 units. Out of inventory
NOTICE: Success with order 19 for 1 units. Sufficient inventory on hand
committed_lines
----------------------------
{{1,1},{7,1},{8,1},{19,1}}
(1 row)
east_ecommerce_data=# SELECT * FROM inventory_request;
time | product_variant_id | sales_transaction_id | qty
----------------------------+--------------------+----------------------+-----
2025-08-21 12:13:51.655896 | 1 | east_5316 | 1
2025-08-21 12:13:51.697622 | 7 | east_5316 | 1
2025-08-21 12:13:51.728591 | 8 | east_5316 | 1
2025-08-21 12:13:51.759148 | 18 | east_5316 | 3
2025-08-21 12:13:51.788984 | 19 | east_5316 | 1
(5 rows)

The row with product variant ID 18 failed to commit (see the fourth notice), but the inventory request was correctly recorded, even though the initial transaction failed!

This demonstrates that with pg_background, we can run work in a separate session and outside the caller’s transaction context, enabling “autonomous” behavior when needed.

plpgsql_check: A powerful linter for PL/pgSQL code

Section titled “plpgsql_check: A powerful linter for PL/pgSQL code”

plpgsql_check is a syntactical checker for PL/pgSQL code. It parses the code inside the routines and identifies many errors that are not typically detected during the initial evaluation of the CREATE PROCEDURE/FUNCTION command.

Identifying problems early is key, as the code created inside the $$/$$ string of a PL/pgSQL function or stored procedure is not compiled or evaluated by PostgreSQL until the procedure and the code path are being executed. This means that syntactical errors may remain undetected for a long time, until that specific code gets executed. Bugs can be dormant in the code for years!

In this example, the ELSE branch will not be executed until next year. It contains a bug (the value list does not match the column list) that no testing will detect. The function also has an unused variable.

CREATE OR REPLACE FUNCTION product_reference.insert_brand_test_linter
(p_id INTEGER, p_label TEXT, p_description TEXT) RETURNS TEXT
AS
$$
DECLARE
v_test_var INTEGER :=0; -- unused variable to test linter
BEGIN
IF current_date< '2025-12-31' THEN
INSERT INTO product_reference.product_brand (id, label, description)
VALUES (p_id, p_label, p_description);
ELSE
INSERT INTO product_reference.product_brand (id, label, description)
VALUES (p_id, 'All new: ' || p_description);
END IF;
RETURN 'Done';
END $$ LANGUAGE plpgsql;
SELECT plpgsql_check_function('product_reference.insert_brand_test_linter', fatal_errors := false);
plpgsql_check_function
-----------------------------------------------------------------------------
error:42601:9:SQL statement:INSERT has more target columns than expressions
Query: INSERT INTO product_reference.product_brand (id, label, description)
-- ^
VALUES (p_id, 'All new: ' || p_description)
warning extra:00000:3:DECLARE:never read variable "v_test_var"

The use of a linter, such as plpgsql_check, helps build and maintain high-quality code. Besides finding mismatched arguments and unused variables, it can also be used to identify dependencies among procedures, functions, views, and tables.

PostgreSQL’s native procedural language is a powerful tool that provides functions, procedures, triggers, flow control, and advanced error handling features. It enables developers to create modular solutions that operate close to the data, reducing unnecessary roundtrips and harnessing the full capabilities of SQL and the database engine.

Modules created in PL/pgSQL leverage ACID compliance and PostgreSQL’s sophisticated data-aware query planner. This avoids writing a lot of custom code and usually performs much, much better. Advanced extensions, such as pg_background, allow developers to break out of the transaction context and spawn independent processes. Linters, such as pgsql_check should be part of every PL/pgSQL developer’s toolbox!

While PL/pgSQL has access to a library of extensions, this library pales in comparison to the vast trove of code available for Python. PL/Python opens that door to the PostgreSQL developer.

PL/Python3u: Running Python inside the database

Section titled “PL/Python3u: Running Python inside the database”

PL/Python3u is a PostgreSQL procedural language extension that uses Python to define procedures, functions, and control flows. PL/Python enables developers to harness the power of Python and its extensive library ecosystem within the database, executing complex processes near the data while minimizing lengthy roundtrips.

PL/Python, more specifically PL/Python3u, uses Python Version 3 and is only available as an untrusted extension. It is considered “untrusted” because it grants full access to the underlying OS and does not utilize PostgreSQL’s security mechanisms. Only a superuser can define PL/Python functions or procedures.

Be extremely cautious when granting access to PL/Python-based procedures and functions. You cannot rely on PostgreSQL managing security. Your code must address all security and access control requirements.

PL/Python functions and procedures use the same building blocks as PL/pgSQL, except that the language tag must be plpython3u (see Table *6.*2 below).

FunctionProcedure
CREATE FUNCTION <function name> ( IN/OUT p_parameter1 <DATATYPE> DEFAULT = <x>; …) IMMUTABLE/STABLE/VOLATILE RETURNS (<DATATYPE>) AS $$ # PL/Python function body $$ LANGUAGE plpython3u;CREATE PROCEDURE <function name> ( IN/OUT p_parameter1 <DATATYPE> DEFAULT = <x>; …) AS $$ # PL/Python function body $$ LANGUAGE plpython3u

Table 6.2: Key building blocks of PL/Python function and procedure definitions

PL/Python also supports anonymous code blocks (executed with DO, without creating a stored function or procedure), just like PL/pgSQL.

Mapping PostgreSQL data types to Python data types

Section titled “Mapping PostgreSQL data types to Python data types”

PostgreSQL data types are mapped to Python data types (see Table *6.*3). Some of the finer distinctions, for example, between INTEGER and BIGINTEGER, get lost in this mapping.

PostgreSQL Data TypePython Data Type
BooleanBool
Smallint, integer, bigint, oidInt
Real, doubleFloat
NumericDecimal
ByteaBytes
Char, text, varcharStr
ArrayList
NullNone
Composite, e.g., recordMapping

Table 6.3: Data type mappings from PostgreSQL to PL/Python

PL/Python offers several mechanisms for interacting with the database. They are defined in the plpy module, which must be imported in the function or stored procedure body.

  1. Direct execution of a query using plpy.execute. plpy.execute (< query -string >``,``< limit >) executes the query and returns the results in a result object. < limit > is an optional parameter and constrains the number of rows that will be returned. This simple approach should only be used for queries that return small result sets, as the whole result set is read into memory.
  2. A prepared query using plpy.prepare and plpy.execute allows the creation of execution plans that can be shared across function calls by storing the plan in the shared Storage Dictionary (SD). This is most useful when the same statement is executed repeatedly with different parameters; it is less useful when the SQL text changes frequently or when the plan is unlikely to be reused.
  3. plpy.cursor provides a cursor that can be used to iterate through very large result sets, without loading the whole result set into memory. plpy.cursor can be used with execution plans or with query strings.

(1) and (3) are illustrated next.

The following example checks all product categories for description strings that start with a lowercase letter and changes them to uppercase. It illustrates the use of plpy.execute with a query string and an iteration through the result set.

CREATE OR REPLACE PROCEDURE product_reference.ensure_description_uppercase()
AS $$
import plpy
rows = plpy.execute("SELECT id, description FROM product_reference.product_category")
for row in rows:
desc = row['description']
if desc and not desc[0].isupper():
# Print the description that needs to be fixed
plpy.notice("This description needs to be fixed: %s" % desc)
# Capitalize the first letter of the description
new_desc = desc[0].upper() + desc[1:]
plpy.notice("Fixed: %s" % new_desc)
# Use % formatting and escape single quotes to create query string
update_sql = (
"UPDATE product_reference.product_category "
"SET description = '%s' WHERE id = %d"
) % (new_desc.replace("'", "''"), row['id'])
plpy.execute(update_sql)
$$ LANGUAGE plpython3u;

Now we modify the code to use the cursor approach to perform the same process. In this example, our cursor retrieves five rows at a time and then iterates through that result set.

CREATE OR REPLACE PROCEDURE product_reference.ensure_description_uppercase_cursor()
AS $$
import plpy
cursor = plpy.cursor("SELECT id, description FROM product_reference.product_category")
while True:
rows = cursor.fetch(5) # fetch 5 rows at a time
if not rows:
break
for row in rows:
desc = row['description']
if desc and not desc[0].isupper():
# Print the description that needs to be fixed
plpy.notice("This description needs to be fixed: %s" % desc)
# Capitalize the first letter of the description
new_desc = desc[0].upper() + desc[1:]
plpy.notice("Fixed: %s" % new_desc)
# Use % formatting and escape single quotes to create query string
update_sql = (
"UPDATE product_reference.product_category "
"SET description = '%s' WHERE id = %d"
) % (new_desc.replace("'", "''"), row['id'])
plpy.execute(update_sql)
$$ LANGUAGE plpython3u;

PL/Python also offers exception handling that is similar to PL/pgSQL. It uses Python’s try:/except/else structure. To catch specific exceptions, the plpy.spiexceptions module defines an exception class for each PostgreSQL error condition, deriving its name from the PostgreSQL error condition.

For example, the PostgreSQL error division_by_zero becomes DivisionByZero, unique_violation becomes UniqueViolation, fdw_error becomes FdwError, and so on. Each of these exception classes inherits from SPIError.

The following example shows how different types of exceptions are handled in PL/Python.

CREATE OR REPLACE FUNCTION product_reference.insert_category(
p_id INTEGER,
p_label TEXT,
p_description TEXT
)
RETURNS TEXT
AS $$
import plpy
from plpy import spiexceptions
try:
sql = (
"INSERT INTO product_reference.product_category (id, label, description) "
"VALUES (%d, '%s', '%s')"
) % (
p_id,
p_label.replace("'", "''"),
p_description.replace("'", "''")
)
plpy.execute(sql)
return "Insert successful"
except spiexceptions.UniqueViolation as e:
return "Unique constraint violation: " + str(e)
except spiexceptions.PrimaryKeyViolation as e:
return "Unique constraint violation: " + str(e)
except plpy.SPIError as e:
return "other error, SQLSTATE %s" % e.sqlstate
except Exception as e:
return "Unknown error: " + str(e)
$$ LANGUAGE plpython3u;

Table *6.*4 lists the PL/Python equivalents of the PL/pgSQL RAISE command. The output of the messages is controlled by log_min_messages and client_min_messages – the same as in PL/pgSQL.

PL/ pgSQL RAISEPL/Python Equivalent
DEBUGplpy.debug (msg, ** kwargs``)
LOGplpy.log (``msg, ** kwargs``)
INFOplpy.info (``msg, ** kwargs``)
NOTICEplpy.notice (msg, ** kwargs``)
WARNINGplpy.warning (msg, ** kwargs``)
ERRORplpy.error (msg, ** kwargs``) – also raises an exception
FATALplpy.fatal (msg, ** kwargs``) – also raises an exception

Table 6.4: PL/Python RAISE equivalents

PL/Python provides transaction control mechanisms that map to PL/pgSQL’s mechanism (see Table *6.*5).

PL/ pgSQLPL/Pyt h on
BEGINNot available. A new transaction block starts immediately after a rollback command. No need to issue a BEGIN command
COMMITplpy.commit ()
ROLLBACKplpy.rollback ()
SAVEPOINTNot available

Table 6.5: PL/Python transaction control

PL/Python provides plpy.subtransaction () to create implicit transaction blocks that ensure a sequence of plpy.execute () either commits as a single transaction or rolls back all changes.

PL/Python3u provides a compelling environment for complex, computationally intensive tasks that rely on third-party libraries. The rise of data science, machine learning, and AI has made Python and PL/Python3u an essential tool for developers. PL/Python is closely integrated with PostgreSQL, enabling control over transactions and handling of database-level exceptions effectively. It has become one of the most popular tools to create data-intensive applications.

PL/Python3u and PL/pgSQL: Which one to use and when?

Section titled “PL/Python3u and PL/pgSQL: Which one to use and when?”

PL/pgSQL’s strength is its close alignment with SQL and the underlying database. Its strong transaction management capabilities and handling of exceptions to the database consistency rules make it a powerful choice for applications focused on ACID-compliant transactional features. Its “trusted” nature also makes it a safe option for many applications.

PL/Python3u excels because of its vast library of solutions and the ease with which they can be integrated. It handles complex, CPU-intensive calculations very well and can leverage existing libraries for math, data science, machine learning, AI, and text processing. It can easily call out to other systems, such as hosted ML or AI systems. However, it is an untrusted language that runs outside of PostgreSQL’s security controls. In practice, teams often start with the language they are most productive in and optimize later, if and when performance or operational constraints require it.

Table *6.*6 summarizes our guidance for when to use PL/Python versus PL/pgSQL.

FeaturePL/ pgSQLPL/Python
SQL-centric✅❌
Transaction-focused✅❌
Compute-intensive operations❌✅
Access to external libraries❌✅
ML and AI execution or integration❌✅
Integration with external solutions❌✅
Trusted✅❌

Table 6.6: A comparison of the key strengths of PL/pgSQl and PL/Python

This chapter covered functions and stored procedures in PostgreSQL. They should be used to create modular code that runs close to the data, reduces roundtrips between the application and the database, and isolates the application from the database layout details. Functions and procedures also define transactional units of work, and PostgreSQL provides various constructs to initiate, commit, or cancel transactions. PostgreSQL supports several procedural languages, and we focused on the two most popular ones, using multiple detailed examples: PL/Python and PL/pgSQL.

The chapter concluded with advice for developers choosing between these two procedural languages, setting the foundation for discussing high-transaction-volume designs and guidelines for writing efficient transactional code.