PostgreSQL:Volatility
lastmod 2026-05-12created 2026-05-125 edits
Function Volatility Categories - VOLATILE, STABLE, IMMUTABLE
Three categories
- VOLATILE - result may differ on every call (default)
- STABLE - guarantees same arguments → same result within the same transaction
- IMMUTABLE - guarantees same arguments → same result, always
STABLE
- Declares that the function does not modify the DB and that its result does not change within the same transaction
- The planner can trust this and optimize by skipping unnecessary repeated calls
- Typical examples:
NOW(),current_user, lookup functions that only SELECT from tables
CREATE FUNCTION get_org_name(org_id UUID)
RETURNS TEXT
LANGUAGE sql
STABLE -- 같은 트랜잭션 내에선 org 이름이 안 바뀜
AS $$
SELECT name FROM orgs WHERE id = org_id;
$$;
Caveats:
- STABLE functions cannot be used as the DEFAULT value of an index expression (only IMMUTABLE can)
- If misclassified, the planner may reuse cached results and return wrong results, so declare it to match the actual behavior.
Key differences
| Attribute | Scope in which calls with the same arguments give the same result | DB state access | Examples |
| | Always, forever (completely independent of DB state) | ❌ Forbidden (cannot use tables/sequences/ | |
| | Same result within a single SQL statement | ✅ Read OK, write ❌ | |
| | May differ on every call | ✅ Both read/write | |
One-line rule of thumb
| Condition | Declaration |
| Never reads the DB and always gives the same answer for the same arguments | |
| Reads the DB but does not write, and gives the same answer within one statement | |
| Everything else | |
Verification matrix
| Declaration | DB read | DB write | FOR UPDATE | random / now | RAISE |
| | ❌ | ❌ | ❌ | ❌ | ✅ |
| | ✅ | ❌ | ❌ | ❌ | ✅ |
| | * | ✅ | ✅ | ✅ | * |
(✅ allowed, ❌ forbidden, * irrelevant)