TExcelTAD
Home › PostgreSQL › PostgreSQL Functions & Procedures

PostgreSQL Functions & Procedures

PostgreSQL lets you store your own code in the database. Functions compute and return a value and can be used inside queries. Procedures perform actions and are started with CALL. You can write them in plain SQL or in PL/pgSQL, PostgreSQL's procedural language with variables, IF, loops and error handling.

A SQL function

The simplest functions are a single SQL expression or query. This one computes a price including VAT:

pgsql · try it yourself
CREATE FUNCTION with_vat(net numeric, rate numeric DEFAULT 0.20)
RETURNS numeric
LANGUAGE sql IMMUTABLE
RETURN round(net * (1 + rate), 2);

SELECT title, price, with_vat(price) AS gross, with_vat(price, 0.07) AS reduced
FROM books
WHERE id <= 3;
CREATE FUNCTION
       title        | price | gross | reduced
--------------------+-------+-------+---------
 The Salt Road      | 14.99 | 17.99 |   16.04
 Harbor Lights      | 12.50 | 15.00 |   13.38
 Signal from Kepler | 18.00 | 21.60 |   19.26
(3 rows)

IMMUTABLE tells the planner the result depends only on the arguments, which allows optimisations and use in indexes. Others are STABLE (doesn't change within a query, e.g. reads tables) and VOLATILE (the default).

Functions that return tables

A function can return a whole result set with RETURNS TABLE (…) or RETURNS SETOF type, and you query it like a table:

pgsql · try it yourself
CREATE FUNCTION books_by_author(author_name text)
RETURNS TABLE (title text, price numeric, published date)
LANGUAGE sql STABLE
AS $
    SELECT b.title, b.price, b.published
    FROM books b JOIN authors a ON a.id = b.author_id
    WHERE a.name = author_name
    ORDER BY b.published
$;

SELECT * FROM books_by_author('Tom Whitfield');
CREATE FUNCTION
         title          | price | published
------------------------+-------+------------
 The Age of Canals      | 24.95 | 2009-04-22
 Empires of Sand        | 27.00 | 2012-09-09
 A Short History of Tea | 19.50 | 2014-10-15
(3 rows)

The body is written between $ dollar quotes, so it can contain single quotes without escaping.

PL/pgSQL: variables, IF and loops

A PL/pgSQL function has a DECLARE section for variables and a BEGIN … END block. SELECT … INTO stores a query result in a variable:

pgsql · try it yourself
CREATE FUNCTION customer_level(cust_id integer)
RETURNS text
LANGUAGE plpgsql
AS $
DECLARE
    total numeric;
BEGIN
    SELECT coalesce(sum(oi.quantity * oi.unit_price), 0) INTO total
    FROM orders o JOIN order_items oi ON oi.order_id = o.id
    WHERE o.customer_id = cust_id AND o.status <> 'cancelled';

    IF total >= 100 THEN
        RETURN 'gold';
    ELSIF total >= 40 THEN
        RETURN 'silver';
    ELSE
        RETURN 'bronze';
    END IF;
END;
$;

SELECT id, first_name, customer_level(id) AS level
FROM customers
WHERE id IN (1, 4, 6, 7, 9)
ORDER BY id;
CREATE FUNCTION
 id | first_name | level
----+------------+--------
  1 | Anna       | gold
  4 | David      | silver
  6 | Farid      | silver
  7 | Gina       | bronze
  9 | Isla       | silver
(5 rows)

Loops and RAISE NOTICE, which prints a message (useful for debugging):

pgsql · try it yourself
DO $
DECLARE
    r record;
    n integer := 0;
BEGIN
    FOR r IN SELECT title, stock FROM books WHERE stock < 4 ORDER BY stock, title LOOP
        n := n + 1;
        RAISE NOTICE '% has % in stock', r.title, r.stock;
    END LOOP;
    RAISE NOTICE '% books need reordering', n;
END;
$;
NOTICE:  Harbor Lights has 0 in stock
NOTICE:  The Age of Canals has 0 in stock
NOTICE:  Winter in Sofia has 1 in stock
NOTICE:  Empires of Sand has 2 in stock
NOTICE:  The Last Orbit has 3 in stock
NOTICE:  5 books need reordering
DO

DO runs an anonymous code block once, without creating a function.

Errors and exceptions

RAISE EXCEPTION stops the function with an error. An EXCEPTION block catches errors, much like try/catch:

pgsql · try it yourself
CREATE FUNCTION safe_ratio(a numeric, b numeric)
RETURNS numeric
LANGUAGE plpgsql
AS $
BEGIN
    IF a < 0 THEN
        RAISE EXCEPTION 'negative input: %', a USING HINT = 'Pass a value >= 0';
    END IF;
    RETURN round(a / b, 3);
EXCEPTION
    WHEN division_by_zero THEN
        RAISE NOTICE 'division by zero, returning NULL';
        RETURN NULL;
END;
$;

SELECT safe_ratio(10, 4) AS ok;
SELECT safe_ratio(10, 0) AS by_zero;
SELECT safe_ratio(-1, 2) AS negative;
CREATE FUNCTION
  ok
-------
 2.500
(1 row)

NOTICE:  division by zero, returning NULL
 by_zero
---------

(1 row)

ERROR:  negative input: -1
HINT:  Pass a value >= 0
CONTEXT:  PL/pgSQL function safe_ratio(numeric,numeric) line 4 at RAISE

Procedures

A procedure doesn't return a value and is run with CALL. Unlike a function, a procedure may COMMIT in the middle, which is useful for long batch jobs. This one places an order and updates stock in one go:

pgsql · try it yourself
CREATE PROCEDURE place_order(cust integer, book integer, qty integer)
LANGUAGE plpgsql
AS $
DECLARE
    new_id integer;
    book_price numeric;
BEGIN
    UPDATE books SET stock = stock - qty WHERE id = book
    RETURNING price INTO book_price;

    INSERT INTO orders (customer_id, order_date, status)
    VALUES (cust, DATE '2025-03-01', 'pending')
    RETURNING id INTO new_id;

    INSERT INTO order_items VALUES (new_id, book, qty, book_price);
    RAISE NOTICE 'order % placed', new_id;
END;
$;

CALL place_order(7, 5, 2);
CALL place_order(7, 16, 3);

SELECT id, stock FROM books WHERE id IN (5, 16);
SELECT o.id, o.customer_id, oi.book_id, oi.quantity FROM orders o JOIN order_items oi ON oi.order_id = o.id WHERE o.id > 20;
CREATE PROCEDURE
NOTICE:  order 21 placed
CALL
ERROR:  new row for relation "books" violates check constraint "books_stock_check"
DETAIL:  Failing row contains (16, Winter in Sofia, 8, 1, 17.80, -2, 2024-12-01, {city,winter}, {"pages": 264, "format": "ebook", "language": "bg"}).
CONTEXT:  SQL statement "UPDATE books SET stock = stock - qty WHERE id = book
    RETURNING price"
PL/pgSQL function place_order(integer,integer,integer) line 6 at SQL statement
 id | stock
----+-------
  5 |    13
 16 |     1
(2 rows)

 id | customer_id | book_id | quantity
----+-------------+---------+----------
 21 |           7 |       5 |        2
(1 row)

The second call fails because book 16 has only one copy (CHECK (stock >= 0)), and since CALL runs as one statement, nothing of that order is saved.

Managing functions

Statement Does
CREATE OR REPLACE FUNCTION … define or redefine (same arguments and return type)
DROP FUNCTION name(arg types) remove it
\df (psql) / information_schema.routines list functions

Test yourself

How do you run a procedure?

  1. SELECT proc()
  2. CALL proc()
  3. EXECUTE proc
  4. RUN proc()

In PL/pgSQL, how do you store a query's result in a variable?

  1. SET var = SELECT ...
  2. SELECT ... INTO var
  3. var <- SELECT ...
  4. LET var = ...

What does RAISE NOTICE do?

  1. Stops the function with an error
  2. Prints an informational message and continues
  3. Logs into a table
  4. Commits the transaction