STABLE is a volatility classification used in PostgreSQL (and derivatives such as Amazon Redshift) when defining or altering a user-defined SQL, PL/pgSQL, or C function. It tells the query planner that the function reads data but does not write it, and that its return value is constant for all calls made inside the same SQL statement. Because the result cannot change during a statement, the planner may evaluate the function once per row or even once per scan, and may cache the output for optimization. Unlike IMMUTABLE, a STABLE function may depend on table contents, configuration parameters, or the current transaction snapshot. Unlike VOLATILE, it cannot contain side effects such as INSERT, UPDATE, DELETE, or calling other volatile functions. Misclassifying volatility can lead to wrong results or unnecessary re-execution, so choosing STABLE when appropriate improves performance without sacrificing correctness. The attribute is applied in CREATE FUNCTION or ALTER FUNCTION and remains until explicitly changed.
CREATE FUNCTION, ALTER FUNCTION, IMMUTABLE, VOLATILE, SECURITY DEFINER, STRICT
PostgreSQL 7.4
PostgreSQL may cache its result within a query, leading to inconsistent data or missed side effects. Always classify based on the most volatile operation inside the function.
Yes. It can run SELECT statements and depend on the current transaction snapshot. It just cannot modify data.
Not mandatory, but using it correctly lets the planner avoid redundant executions and can noticeably speed up queries that call the function many times.
Use ALTER FUNCTION function_name(arg_types) STABLE; The change takes effect immediately for new sessions.