← Back to PostgreSQL, page 3

postgresql-0044 · Medium mid

Write a PL/pgSQL function that returns a table, and choose between IMMUTABLE, STABLE and VOLATILE.

A function with RETURNS TABLE(...) and RETURN QUERY returns rows usable in FROM. Volatility tells the planner what it may assume: IMMUTABLE for pure computations (allowed in indexes), STABLE for functions that read the database but do not change it within a statement, and VOLATILE (the default) for anything else. Mislabelling a function can return wrong results.

Full answer

Schema and sample rows:

sql
CREATE TABLE sales (region text, amount numeric(10,2), sold_on date);
INSERT INTO sales VALUES ('north', 100, '2026-11-01'), ('north', 250, '2026-11-15'), ('south', 75, '2026-11-20'), ('south', 300, '2026-12-01');

CREATE FUNCTION gst(amount numeric) RETURNS numeric
LANGUAGE sql IMMUTABLE AS $$ SELECT round(amount * 0.18, 2) $$;

CREATE FUNCTION region_summary(since date)
RETURNS TABLE (region text, orders bigint, revenue numeric, tax numeric)
LANGUAGE plpgsql STABLE AS $$
BEGIN
  RETURN QUERY
    SELECT s.region, count(*), sum(s.amount), sum(gst(s.amount))
    FROM sales s
    WHERE s.sold_on >= since
    GROUP BY s.region
    ORDER BY s.region;
END;
$$;
sql
SELECT * FROM region_summary('2026-11-10');

Result:

text
 region | orders | revenue |  tax
--------+--------+---------+-------
 north  | 1      | 250.00  | 45.00
 south  | 2      | 375.00  | 67.50
(2 rows)
sql
SELECT proname, provolatile FROM pg_proc WHERE proname IN ('gst', 'region_summary') ORDER BY proname;

Output:

text
    proname     | provolatile
----------------+-------------
 gst            | i
 region_summary | s
(2 rows)
sql
CREATE FUNCTION bad_now_label() RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT now()::text $$; CREATE TABLE t (x text); CREATE INDEX ON t ((x || bad_now_label())); CREATE INDEX ON t ((x || now()::text));

PostgreSQL returns:

text
ERROR:  functions in index expression must be marked IMMUTABLE

region_summary returns rows filtered by date, with tax computed by the IMMUTABLE gst helper. Columns in the function body are qualified with s. because RETURNS TABLE column names become variables inside PL/pgSQL, and an unqualified region would be ambiguous. pg_proc records volatility as i, s or v. The last run shows the danger of lying: PostgreSQL trusts the IMMUTABLE label and accepts an index using bad_now_label(), whose value actually changes, while using now() directly in an index fails with 'functions in index expression must be marked IMMUTABLE'.

sql
CREATE TABLE sales (region text, amount numeric(10,2), sold_on date);
INSERT INTO sales VALUES ('north', 100, '2026-11-01'), ('north', 250, '2026-11-15'), ('south', 75, '2026-11-20'), ('south', 300, '2026-12-01');

CREATE FUNCTION gst(amount numeric) RETURNS numeric
LANGUAGE sql IMMUTABLE AS $$ SELECT round(amount * 0.18, 2) $$;

CREATE FUNCTION region_summary(since date)
RETURNS TABLE (region text, orders bigint, revenue numeric, tax numeric)
LANGUAGE plpgsql STABLE AS $$
BEGIN
  RETURN QUERY
    SELECT s.region, count(*), sum(s.amount), sum(gst(s.amount))
    FROM sales s
    WHERE s.sold_on >= since
    GROUP BY s.region
    ORDER BY s.region;
END;
$$;

SELECT * FROM region_summary('2026-11-10');

SELECT proname, provolatile FROM pg_proc WHERE proname IN ('gst', 'region_summary') ORDER BY proname;

CREATE FUNCTION bad_now_label() RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT now()::text $$; CREATE TABLE t (x text); CREATE INDEX ON t ((x || bad_now_label())); CREATE INDEX ON t ((x || now()::text));

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • RETURNS TABLE with RETURN QUERY returns rows
  • Volatility guides the planner
  • IMMUTABLE is required in indexes
  • Qualify columns to avoid name clashes
  • Mislabelled volatility gives wrong results

Common mistakes

  • Marking functions IMMUTABLE that read tables or time
  • Unqualified column names clashing with OUT parameters

Follow-ups

  • When would you use LANGUAGE sql instead of plpgsql?
  • What does PARALLEL SAFE mean?

Tips

  • Explain the name clash