Sub topic 7
Declaring volatility correctly
This chapter covers the three volatility categories for SQL functions in PostgreSQL, what each one promises the planner, and what goes wrong when the promise is false. It assumes you can write a basic CREATE FUNCTION ... LANGUAGE sql and read an EXPLAIN plan.
What volatility means
Every function has a volatility category. It is a promise you make to the planner about how the function behaves across calls. The planner uses the promise to decide whether it may skip calls, reuse results, evaluate the function early, or use it in an index.
There are three categories:
| Category | Promise | Typical examples |
|---|---|---|
| `IMMUTABLE` | Same arguments always give the same result, forever, with no database lookups and no dependence on settings. | `lower(text)`, `abs(numeric)`, a tax calculation from two arguments |
| `STABLE` | Within a single statement, same arguments give the same result. May read the database but never modifies it. | `now()`, a lookup of a rate in a table |
| `VOLATILE` | The result can change between any two calls, even inside one statement. May modify the database. | `random()`, `nextval()`, a function that runs `INSERT` |
If you write nothing, the function is VOLATILE. That default is always safe, but it gives the planner the least freedom.
Declaring it
Put the category anywhere among the options between RETURNS and the body:
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.20)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
AS $$
SELECT price * (1 + rate);
$$;
SELECT add_tax(100);
SELECT add_tax(100, 0.05);add_tax uses only its arguments and the built-in * and + operators on numeric. Nothing outside the arguments can change its answer, so IMMUTABLE is correct.
What each category allows the planner to do
IMMUTABLE
An immutable call with constant arguments is evaluated once, at planning time, and replaced by its result. For example, WHERE price > add_tax(100) becomes a comparison against a constant, which can use an ordinary index on price.
Only immutable functions may appear in:
- Index expressions, such as
CREATE INDEX ON customers (full_name(first, last)). - Index predicates (the
WHEREclause of a partial index). - Generated columns (
GENERATED ALWAYS AS (...) STORED).
STABLE
A stable function is not folded at planning time, but it can be evaluated once per scan instead of once per row. In an index scan condition such as WHERE created_at > my_stable_func(), the planner can evaluate the function once at the start of the scan and use the value as an index search key. A volatile function in that position forces a filter that runs for every row, and the index cannot be used for it.
VOLATILE
The planner must call the function every time its result is needed, in the order the query implies. It cannot reorder, merge, or skip calls. A volatile function in a WHERE clause is evaluated for each candidate row.
A volatile function also sees the effects of commands it has already run. A STABLE or IMMUTABLE function uses the snapshot of the query that called it, so it does not see changes made by that query.
Choosing the category: a decision procedure
Ask these questions in order and stop at the first "yes":
- Does the function modify the database, call
nextval,random(), or any other volatile function? UseVOLATILE. - Does it read any table, any setting (such as
current_setting,search_path, orTimeZone), the current time, or the current user? UseSTABLEat most. - Does it depend only on its arguments, using only immutable operations? Use
IMMUTABLE.
A function's category cannot be stricter than the functions it calls. If the body calls a STABLE function, your function is at most STABLE.
-- Assumes a table orders(id int, customer_id int, ordered_at timestamptz, total numeric)
CREATE FUNCTION recent_orders(p_customer_id int, p_limit int DEFAULT 10)
RETURNS TABLE (order_id int, ordered_at timestamptz, total numeric)
LANGUAGE sql
STABLE
AS $$
SELECT o.id, o.ordered_at, o.total
FROM orders AS o
WHERE o.customer_id = p_customer_id
ORDER BY o.ordered_at DESC
LIMIT p_limit;
$$;
SELECT * FROM recent_orders(42, 5);recent_orders reads a table but does not change it, so STABLE is correct. IMMUTABLE would be wrong: the same arguments give different results after new orders are inserted.
Immutable is a promise, not a check
PostgreSQL does not verify what you declare for a SQL function body beyond a few restrictions. For example, a STABLE or IMMUTABLE function cannot contain a data-modifying statement, and PostgreSQL raises an error if you try. But it does not detect that an IMMUTABLE function reads a table. The planner will believe you.
Failure mode 1: the stale constant
-- Assumes a table tax_rates(region text primary key, rate numeric)
CREATE FUNCTION region_rate(p_region text)
RETURNS numeric
LANGUAGE sql
IMMUTABLE -- WRONG: reads a table
AS $$
SELECT rate FROM tax_rates WHERE region = p_region;
$$;
PREPARE q AS SELECT region_rate('EU');With a constant argument, the planner may fold region_rate('EU') into a literal when it plans the query. If a prepared statement keeps a cached plan, or a view definition is inlined and planned early, the old rate can stay in the plan after tax_rates is updated. The result is wrong answers with no error. The correct declaration is STABLE.
Failure mode 2: a broken index
If you build an index on an expression that uses a function wrongly marked IMMUTABLE, the index stores values computed at insert time. When the real answer changes, such as when a timezone setting or a lookup table changes, the index no longer matches what the function returns. Queries using the index return wrong rows, and REINDEX is the only repair.
A common instance is a function that casts timestamptz to date. The cast depends on the session TimeZone setting, so it is STABLE, not IMMUTABLE. Wrapping it in a function labeled IMMUTABLE makes the index lie when sessions use different time zones. If you need a date in a fixed zone, make the zone explicit:
CREATE FUNCTION utc_date(ts timestamptz)
RETURNS date
LANGUAGE sql
IMMUTABLE
AS $$
SELECT (ts AT TIME ZONE 'UTC')::date;
$$;Here the zone is part of the expression, so the result depends only on the argument.
Failure mode 3: labeling too conservatively
Marking a pure function VOLATILE (by omission) is safe but slow. It cannot be used in an index expression, and it is called for every row where a stable or immutable function could have been called once. Declare the strongest category that is true.
Interaction with STRICT
STRICT and volatility are independent options and are often written together:
CREATE FUNCTION full_name(first_name text, last_name text)
RETURNS text
LANGUAGE sql
IMMUTABLE STRICT
BEGIN ATOMIC
SELECT first_name || ' ' || last_name;
END;IMMUTABLE says the result depends only on the arguments. STRICT says a NULL argument returns NULL without running the body. Together they let the planner treat the call as a pure function that it can fold or inline.
Volatility and the snapshot
The difference between STABLE and VOLATILE matters inside a single statement that also changes data. Consider a function that counts rows:
-- Assumes a table items(id serial primary key, label text)
CREATE FUNCTION item_count()
RETURNS bigint
LANGUAGE sql
VOLATILE
AS $$
SELECT count(*) FROM items;
$$;
WITH ins AS (
INSERT INTO items (label) VALUES ('x') RETURNING id
)
SELECT item_count() FROM ins;Data-modifying WITH queries and the outer query share one snapshot, so the new row is not visible to item_count() even though it is VOLATILE. The snapshot rule that matters is a different one: a VOLATILE function gets a fresh snapshot for each command inside it, and a STABLE function reuses the caller's snapshot. This shows up when a volatile function is called repeatedly in a function body that also modifies data. If you need a function to see changes made earlier in the same transaction by separate statements, both categories do, because those statements have already committed their effects to the transaction's view.
Changing the category later
You can change the category without recreating the function:
ALTER FUNCTION region_rate(text) STABLE;Changing IMMUTABLE to something weaker does not repair indexes or stored plans built on the old promise. Rebuild any index that used the function with REINDEX, and expect cached plans to be replanned on the next invalidation.
Checking what you have
The catalog records the category in pg_proc.provolatile: i for immutable, s for stable, v for volatile.
SELECT proname, provolatile
FROM pg_proc
WHERE proname IN ('add_tax', 'recent_orders', 'full_name');Summary of rules
- The default is
VOLATILE. Declare something stronger only when it is true. - Reading a table, a setting, the clock, or the current role rules out
IMMUTABLE. - Modifying data, using sequences, or calling
random()requiresVOLATILE. - Index expressions, partial-index predicates, and generated columns require
IMMUTABLE. - A wrong
IMMUTABLElabel does not raise an error. It produces stale results, so review it as carefully as you would a cache invalidation rule.
Exercise
A function current_rate(p_region text) runs SELECT rate FROM tax_rates WHERE region = p_region. A colleague marks it IMMUTABLE so it can be used in a generated column. What is wrong, which category is correct, and what should the colleague do instead of the generated column?
Show answer
The function reads a table, so its result changes when tax_rates changes. IMMUTABLE makes the planner and the stored column assume the result never changes, so stale values can persist. The correct category is STABLE. Because a generated column requires an immutable expression, it cannot call this function. The colleague should compute the rate at query time (for example in a view or by calling the STABLE function in the query), or store the rate in an ordinary column that is set explicitly when the row is written.
Exercise
Which category fits each function? (a) SELECT $1 * $2, (b) a function that returns now() truncated to the day, (c) a function that inserts an audit row and returns its id, (d) SELECT upper($1) for a text argument.
Show answer
(a) IMMUTABLE, because it depends only on its arguments. (b) STABLE, because now() is fixed within a transaction but changes between transactions. (c) VOLATILE, because it modifies the database. (d) IMMUTABLE in most cases, but upper depends on the collation of the argument, which is fixed for a given column or expression, so it is treated as immutable.