Skip to the stories
Windows & PowerShell

PostgreSQL Function Volatility: How STABLE Cut a Query from 52 Seconds to 1.696 ms

  • Grant Fritchey
  • 791 views

PostgreSQL’s volatility labels guide query planning. In a test on nearly 600 million rows, marking a function STABLE reduced execution from about 52 seconds to 1.696 ms.

PostgreSQL Function Volatility: How STABLE Cut a Query from 52 Seconds to 1.696 ms

A PostgreSQL function’s volatility label can change how often the planner runs it—and that can make a dramatic difference to a query. In one test, adding STABLE to a function cut execution time from about 52 seconds to 1.696 milliseconds, while reported buffer use fell from 8,000,062 to four.

That result came from a deliberately large example, so don’t expect the same speedup in every workload. The practical lesson is broader: PostgreSQL defaults user functions to VOLATILE. If a function’s behavior supports a stricter label, declaring it can give the planner more room to optimize. The label must describe the function accurately, though; an incorrect one can produce wrong results without a warning.

What the three labels tell PostgreSQL

Volatility describes how a function’s result can change, and whether the function can modify data. PostgreSQL uses that information when planning a query: it can decide whether a call must be repeated, can be reused during a statement, or can be treated as a constant. The labels are VOLATILE, STABLE and IMMUTABLE; the default is VOLATILE. The PostgreSQL documentation describes the label as a promise about the function’s behavior.

LabelBehaviorPlanner implicationsIndex expressions
VOLATILEMay modify data, and its result can change between calls.The planner must allow for a fresh result each time it is referenced.Not permitted.
STABLEDoes not modify data; the same inputs produce the same result within a single statement.The planner can reuse a result when the inputs are unchanged.Not permitted.
IMMUTABLEDoes not modify data; the same inputs always produce the same result.The planner can fold a call with constant inputs into a constant.Required for functions in index expressions.

Choose the label the function can support

VOLATILE is the broadest category. It applies when a function can change database data, or when repeated calls with the same arguments can return different values. The planner cannot assume that a call is safe to run once and reuse, so it must account for repeated evaluation.

A function that only contains a SELECT can still be volatile. What matters is the behavior of the whole function, including any functions it calls. For example, TIMEOFDAY can change during query execution, so its value may differ from row to row. RANDOM also returns changing results. By contrast, CURRENT_TIMESTAMP and NOW() return the same value throughout a statement, so they are examples of stable behavior.

STABLE functions must not modify database data, directly or through calls to other functions. They must also return the same result for the same inputs within a single statement. The data they read may change between statements: the label does not promise that a lookup will return the same result tomorrow. It says the result remains consistent for the relevant execution context.

When a stable function receives the same inputs wherever it is used in a statement, PostgreSQL can evaluate it once and reuse the result. That can matter when the function appears in a condition applied to many rows. The label is appropriate only when the function’s own behavior and everything it calls meet the same requirement.

IMMUTABLE makes a stronger promise: identical inputs must always yield identical results. Neither stable nor immutable functions may modify data, but immutable functions must not depend on information that can change between statements. With constant inputs, the planner can evaluate an immutable call during planning and use its result as a constant.

Index expressions have a stricter requirement. A function used in an index must be IMMUTABLE, because the index stores values computed from the function. If those results could change while the indexed row remains the same, the stored entries could stop matching the function’s current output. A stable function can be useful in a query condition, but it does not qualify for an index expression.

A test on a table with nearly 600 million rows

The performance example uses a database previously used for a “Fun With Radios” presentation. Its reports.location_info table had been artificially expanded to close to 600 million rows. A PL/pgSQL function, reports.find_nearest_location, takes latitude, longitude and an optional radius. It builds a geography point, finds the nearest location within that radius, and returns its ID.

CREATE OR REPLACE
FUNCTION reports.find_nearest_location(p_lat NUMERIC,
p_lon NUMERIC,
p_radius_km NUMERIC DEFAULT 5.0)
RETURNS bigint
LANGUAGE plpgsql
--STABLE
AS $$
DECLARE
v_location_id bigint;
v_point geography;
BEGIN
v_point := ST_SetSRID(ST_MakePoint(p_lon, p_lat), 4326);
-- Find the nearest location within radius
SELECT
ll.location_id
INTO
v_location_id
FROM
reports.location_lookup AS ll
WHERE
ST_DWithin(ll.center_point, v_point, p_radius_km * 1000)
ORDER BY
ST_Distance(ll.center_point, v_point)
LIMIT 1;
RETURN v_location_id;
END;
$$;

In the first run, STABLE is commented out. PostgreSQL therefore uses the default, VOLATILE. The function is called in this count query:

SELECT COUNT(*)
FROM reports.location_info
WHERE location_info_id = reports.find_nearest_location(42.0, -71.5, 5.0);

With the function treated as volatile, the query took about 52 seconds. Its EXPLAIN ANALYZE output, collected with BUFFERS, showed roughly 8,000,062 buffers. The function’s arguments are constant in the query, but the volatile label prevents the planner from assuming that each evaluation will return the same result.

In the second run, the function is rebuilt with STABLE declared. The same query took 1.696 milliseconds and used four buffers, according to the corresponding plan. In this case, PostgreSQL could evaluate the function once, then use the returned location ID to perform a single indexed lookup in location_info.

Explain plan with ANALYZE and BUFFERS for the VOLATILE query, showing roughly 52 seconds and 8,000,062 buffers
Explain plan for the STABLE query, showing 1.696 milliseconds and four buffers

The example is contrived, but it makes the planning effect easy to see. A function that must be recalculated as rows are checked can prevent the surrounding query from using a cheaper plan. Once the function can honestly be marked stable, PostgreSQL can reuse its result and make a direct lookup. The reported timing is specific to this setup; the general benefit depends on the query, function and data.

Check the labels in your schemas

The pg_proc system catalog stores a function’s volatility in provolatile. This query lists user functions outside PostgreSQL’s built-in schemas and excludes extension-owned functions:

SELECT
ns.nspname AS schema_name,
p.proname AS function_name,
p.provolatile AS volatility
FROM
pg_proc AS p
JOIN pg_namespace AS ns ON
ns.oid = p.pronamespace
WHERE
p.prokind = 'f'
AND ns.nspname NOT IN ('pg_catalog', 'information_schema')
AND ns.nspname NOT LIKE 'pg\_toast%'
AND NOT EXISTS (
SELECT
1
FROM
pg_depend d
WHERE
d.objid = p.oid
AND d.deptype = 'e'
);

The catalog values are v for VOLATILE, s for STABLE and i for IMMUTABLE. Reviewing the results can help identify functions that rely on the default label, so their behavior can be checked and classified deliberately.

Make the declaration explicit

PostgreSQL’s guidance is to use the strictest volatility category that accurately describes a function. That applies to volatile functions too: writing VOLATILE makes the intent clear to the next person reading the code, rather than leaving them to guess whether the default was chosen deliberately.

There is broad agreement on this practice. The PostgreSQL documentation recommends accurate labels for better optimization. An AWS Database Blog explanation describes how the categories help the planner decide when results can be reused or must be recalculated. A Microsoft article about function optimization for Azure also recommends choosing the strictest valid category.

The risk is that PostgreSQL does not verify whether a declared label matches the function’s actual behavior. If a function that can change its result is marked STABLE or IMMUTABLE, the planner may reuse a value when it should run the function again. PostgreSQL will not necessarily raise an error or warn you; the query can simply return incorrect results. Check the function and its dependencies before tightening its label.

Volatility is one kind of function annotation. PostgreSQL also supports parallel-safety labels—PARALLEL SAFE, PARALLEL RESTRICTED and PARALLEL UNSAFE—which describe whether functions can run in parallel query plans. The parallel-safety documentation explains those categories.

For existing databases, start by inspecting the functions in your own schemas, then verify each function’s behavior before changing its label. For new functions, make the volatility declaration part of the definition. Accurate labels communicate intent and can give PostgreSQL choices that improve execution plans; the test above shows how consequential that choice can be.

Source: Grant Fritchey · www.red-gate.com

Neighbouring cells