PostgreSQL function volatility: how one keyword cut a query from 52s to 1.7ms (Learning PostgreSQL with Grant)

Comments 0

Share to social media

Function volatility in PostgreSQL is a label (VOLATILE, STABLE or IMMUTABLE) that tells the query optimizer how a function behaves.

Marking a function STABLE or IMMUTABLE where it’s valid lets PostgreSQL run it once, instead of once per row. In my test, that took one query from 52 seconds to 1.7 milliseconds.

I only discovered volatility recently, and it deserves more attention than it gets. This guide covers what each level means, a worked example with explain plans, and why you should label every function you write.

New to PostgreSQL functions?

Start with my guide to functions and procedures in PostgreSQL

This guide is part of “Learning PostgreSQL with Grant” – see the full series here.

What is function volatility in PostgreSQL?

The PostgreSQL documentation calls the volatility of a function a “promise” to the optimizer for how a given function is going to behave.

With the knowledge in hand of how this function is likely to deal with data, the optimizer can make different choices for the execution of the code.

A brief history of function volatility in PostgreSQL

Function volatility was originally introduced to PostgreSQL back in version 7, but it wasn’t really ‘enforced’ until version 8. So, it’s been around a while now – at the time of publication in November 2026, version 19 is the latest!

There are three PostgreSQL function volatility levels: VOLATILE, STABLE, and IMMUTABLE. The default is VOLATILE.

Here’s how the three levels compare.

The three function volatility levels in PostgreSQL explained

LevelCan modify data?Result guaranteeWhat the optimizer can doUsable in an index expression?Examples
VOLATILE (default)YesNone; can change on every callMust re-run the function for every reference or rowNoRANDOM(), TIMEOFDAY()
STABLENoSame result for the same inputs within a single statementCan run once and reuse the resultNoCURRENT_TIMESTAMP, NOW()
IMMUTABLENoSame result for the same inputs, foreverCan fold the call into a constantYesABS(), LOWER()

What does VOLATILE mean in PostgreSQL?

The lowest level of volatility is the default one: VOLATILE. A VOLATILE function can do pretty much anything with the data, up to (and including) data modification.

Because of this, the optimizer can’t really assume anything about the function, so must reevaluate the function each time it’s referenced across any number of rows and actions.

Simply put, there’s no way to be sure, for a given call to the function, just what it may do.

Even if the code within a function is just a SELECT statement, for example, certain functions can change the values returned as the query they’re used in executes.

Case in point: the TIMEOFDAY function gets updated throughout the execution of a query, so its value could be different on every row.

On the other hand, the value of the CURRENT_TIMESTAMP function will be the same for all rows in a given query.

What does STABLE mean in PostgreSQL?

In order to be labeled as STABLE, the function cannot be changing data within the database.

Any code within the function (or even calls to other functions that manipulate the data in the database), will turn this from a STABLE function into one that should be labeled VOLATILE.

(We’ll save a discussion for using the label, or just the default, for later on in this guide.)

Additionally, the values for all the rows within the statements in the function must not change for a given set of inputs.

Functions such as TIMEOFDAY or RANDOM return different results, which makes any query using them VOLATILE. The same applies to any function you call inside your function (or anything else) that can return different data for the same input values: it’s no longer STABLE.

Only once you know that data will always be the same for the query/queries involved, can you label it a STABLE function.

STABLE in practice: how the optimizer reuses results

If the STABLE function was going to be called as part of the SELECT statement of a query, but the values passed are all the same, then the optimizer can reference this function a single time.

It’ll then get the value returned, and never execute it again within the query and transaction in question, within that statement.

And what about indexing? Well, if you create an index that uses a function, that function must be labeled as STABLE in order to be used within the index.

The key thing to remember about STABLE: when I say the data can’t change, that’s only within a given execution context.

It’s not saying that “running the function now returns three rows” or “if I run the function tomorrow, it returns five rows, because the data is changed.”

That’s still a STABLE function. The data can, and will, change in a database. The question is, does it change within the execution context of the query in the function?

If not, the function is safe to mark as STABLE.

Get started with PostgreSQL – free book download

‘Introduction to PostgreSQL for the data professional’, written by Grant Fritchey and Ryan Booz, covers all the basics of how to get started with PostgreSQL.
Download your free copy

What does IMMUTABLE mean in PostgreSQL?

There’s only one real difference between the STABLE and IMMUTABLE levels of function volatility in PostgreSQL: neither can be marked on a function that manipulates data. After that, there’s a big difference between them.

With STABLE, the results are simply the same for a given input.

With IMMUTABLE, they’re the same forever.

Put simply – if you can’t always guarantee identical results, don’t label a function IMMUTABLE in PostgreSQL!

In fact, IMMUTABLE should probably be saved for those few functions that return results that are either unchanging within your database, or changing extremely slowly – slow enough that multiple references within a given execution context will always return an identical value.

Marking a function as IMMUTABLE basically means the optimizer will likely fold the execution of the function into a constant for use in the rest of the explain plan.

Function volatility in action: a 52-second query down to 1.7ms

I’ve got a very contrived example of function volatility in PostgreSQL as I want you to see just how radical the difference in behavior is.

The example function and query

For the example, I’ve got a simple little database – one previously used in my Fun With Radios presentation. Here, I’ve artificially inflated the amount of data in the location_info table to close to 600 million rows.

And I’ve got a function – find_nearest_location – that looks like this:

The important thing to note is that STABLE is currently commented out – so, when this function is created, it defaults to VOLATILE.

I’m going to use the function in this query:

When I run this query, it takes about 52 seconds to execute. Here’s the explain plan:

Explain plan (ANALYZE, BUFFERS) for the VOLATILE version of the query, showing roughly 52 seconds execution time and 8,000,062 buffers

I used both ANALYZE and BUFFERS to get a complete set of data. Before we talk about what this query is up to, though, let’s change the rules.

I’m going to remove the comment markers from STABLE and rebuild the query. Doing so results in this explain plan:

Explain plan for the STABLE version of the query, showing 1.696 ms execution time and 4 buffers

First thing that ought to jump out at you is that the execution time is 1.696 milliseconds.

That’s right – from about 52 seconds to 1.696 milliseconds.

I’d say that’s a win, but how is it possible?

Why STABLE is so much faster than VOLATILE

Remember STABLE says that, for a given input, we’re going to have the same output – however, VOLATILE doesn’t know what the output will be.

In the first query (VOLATILE), it executes the function every time to validate the rows. STABLE, on the other hand, executes the function in the second query just once – and then reuses the value to retrieve exactly what’s needed.

That reduces the buffers all the way down from 8,000,062 to just 4! In short: a single lookup on the index.

As I said, it’s a contrived example, but one that illustrates the benefits really clearly. If your functions meet the criteria for STABLE, I’d sure recommend using that.

And if your function meets the criteria for IMMUTABLE? Sure, use that too.

Ultimately, these options give the optimizer superior choices in how it’s going to resolve your query. Those choices can result in radical improvements in performance.

A couple more points about the behavior. To reiterate, if you label something that’s VOLATILE as STABLE, you could see radically different results coming back from the query – and you won’t get a warning or error from PostgreSQL. It’ll just execute your poorly-labeled code.

How to check function volatility in your PostgreSQL database

If you want to see a listing of functions within your database and what they have their volatility set to, you can use this:

Best practice: always label function volatility in PostgreSQL

The official PostgreSQL documentation on function volatility is extremely clear:

For best optimization results, you should label your functions with the strictest volatility category that is valid for them.

Then there’s the AWS blog with its nice, long, article on exactly why you should be using function classification, including:

By labeling functions as IMMUTABLE, STABLE, or VOLATILE, you help the query planner optimize performance by determining when results can be cached and reused or recalculated.

There’s also an article on performance enhancements for functions on Azure that says:

For best optimization results, you should label your functions with the strictest volatility category that is valid for what the code of the function needs to do.

Why you should label every PostgreSQL function

I recognize that I cannot tell you what to do. However, I do want you to know that there is broad agreement on this point: you should label your functions in PostgreSQL with their volatility.

To see how common this is in practice, I ran a number of searches across several AI engines. Only around 40% of the recently published example code showed volatility labels in its functions, so you are more likely than not to be missing them in the sample code you read.

Heck, my own sample code doesn’t even have them either! The point remains, though: label your functions.

Even if a function is VOLATILE, label it anyway. I know it’s the default, but an explicit label tells the next reader “I intended this one to be VOLATILE” rather than just, “I forgot.”

Clarity and intent matter so much in code. Accurate labels can also bring real performance benefits, because marking a function STABLE or IMMUTABLE where appropriate gives the planner room to optimize.

But, even regardless of that – label your functions in PostgreSQL!

Conclusion: label every function

In a conclusion you’re not supposed to introduce new topics. However, I’ll also mention that there’s labels for parallelism as well as volatility: PARALLEL SAFE, PARALLEL RESTRICTED, and PARALLEL UNSAFE.

You might want to look them up and decide how it fits in your code as well.

As you can see, volatility labeling is important, but we’re not (yet) too great at ensuring it’s a fundamental aspect of all our code.

Going forward, I’m going to change that (for obvious reasons) – and I think you should do the same. Knowing that you can get a free performance enhancement by adding one word to your code is really hard to argue with.

Free desktop tool for fast PostgreSQL monitoring and diagnostics

Stay in control of PostgreSQL performance with Redgate pgNow – a free desktop tool for fast, focused diagnostics. No agents, no setup, just actionable insights when you need them.
Learn more & download now

FAQs

1. What is the default volatility of a PostgreSQL function?

A PostgreSQL function is VOLATILE by default if you don’t specify a label. VOLATILE is the least restrictive level: the function can modify data, and its result can change between calls, so the optimizer must re-run it every time it’s referenced. Adding STABLE or IMMUTABLE, where valid, lets PostgreSQL optimize more aggressively.

2. What is the difference between STABLE and IMMUTABLE in PostgreSQL?

Neither can modify data, but they differ in how long results stay the same. A STABLE function returns the same result for the same inputs within a single query execution. An IMMUTABLE function returns the same result for the same inputs forever, which lets the optimizer fold the call into a constant.

3. Can I use a STABLE function in an index?

No. Functions used in an index expression must be IMMUTABLE. An index stores computed values, which would become wrong if the function’s result could change. A STABLE function works fine in a query’s WHERE clause, but PostgreSQL rejects it in an index definition.

4. What happens if I label a function with the wrong volatility?

PostgreSQL doesn’t check that the label matches what the code does, and it won’t warn you. If you mark a VOLATILE function as STABLE or IMMUTABLE, the optimizer may reuse one result when it should re-run the function, so queries can quietly return incorrect data. Use the strictest label your function can honestly support.

5. How do I check the volatility of my PostgreSQL functions?

Query the pg_proc system catalog and read the provolatile column: v means VOLATILE, s means STABLE, and i means IMMUTABLE. Join to pg_namespace to exclude system schemas, as in the query shown earlier in this guide. Run it against your own schemas to find functions still relying on the default.

This document contains proprietary information and is protected by copyright law.

Copyright © 2026 Red Gate Software Limited. All rights reserved

Article tags

About the author

Grant Fritchey

See Profile

Grant Fritchey is a Data Platform MVP with over 30 years' experience in IT, including time spent in support and development. He has worked with SQL Server since 6.0 back in 1995. He has also developed in VB, VB.NET, C#, and Java. Grant has written books for Apress and Simple-Talk. Grant presents at conferences and user groups, large and small, all over the world. Grant volunteers for PASS and is on the Board of Directors as the Immediate Past President. He joined Redgate Software as a product advocate January 2011.

Grant Fritchey's contributions