{"id":113631,"date":"2026-11-25T12:00:00","date_gmt":"2026-11-25T12:00:00","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=113631"},"modified":"2026-10-19T13:10:16","modified_gmt":"2026-10-19T13:10:16","slug":"postgresql-function-volatility","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/databases\/postgresql\/postgresql-function-volatility\/","title":{"rendered":"PostgreSQL function volatility: how one keyword cut a query from 52s to 1.7ms (Learning PostgreSQL with Grant)"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Function volatility in <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/postgresql\/\" target=\"_blank\" rel=\"noreferrer noopener\">PostgreSQL<\/a> is a label (<code>VOLATILE<\/code>, <code>STABLE<\/code> or <code>IMMUTABLE<\/code>) that tells the query optimizer how a function behaves.<\/strong> <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Marking a function <code>STABLE<\/code> or <code>IMMUTABLE<\/code> where it\u2019s valid lets PostgreSQL run it once, instead of once <em>per row<\/em>. In my test, that took one query from 52 seconds to 1.7 milliseconds.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<div id=\"callout-block_ded691b9bd63ba6e5679ae72658617fa\" class=\"callout alignnone\">\n    <div class=\"child-last:mb-0 child-first:mt-0 bg-gray-50 dark:bg-gray-950 p-4xl my-3xl\">\n\n<p class=\"wp-block-paragraph\"><strong>New to PostgreSQL functions?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Start with my <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/postgresql\/functions-and-procedures-learning-postgresql-with-grant\/\" target=\"_blank\" rel=\"noreferrer noopener\">guide to functions and procedures in PostgreSQL<\/a><\/p>\n\n<\/div>\n<\/div> \n\n\n<p class=\"wp-block-paragraph\"><em>This guide is part of &#8220;Learning PostgreSQL with Grant&#8221; &#8211; see the full series <a href=\"https:\/\/www.red-gate.com\/simple-talk\/collections\/series-learning-postgresql-with-grant\/\" target=\"_blank\" rel=\"noreferrer noopener\">here<\/a>.<\/em><\/p>\n\n\n\n<h2 id=\"h-what-is-function-volatility-in-postgresql\" class=\"wp-block-heading\">What is function volatility in PostgreSQL?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The <a href=\"https:\/\/www.postgresql.org\/docs\/9.0\/xfunc-volatility.html\" target=\"_blank\" rel=\"noreferrer noopener\">PostgreSQL documentation<\/a> calls the volatility of a function a \u201cpromise\u201d to the optimizer for how a given function is going to behave. <\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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. <\/p>\n\n\n\n<div id=\"callout-block_ded691b9bd63ba6e5679ae72658617fa\" class=\"callout alignnone\">\n    <div class=\"child-last:mb-0 child-first:mt-0 bg-gray-50 dark:bg-gray-950 p-4xl my-3xl\">\n\n<p class=\"wp-block-paragraph\"><strong>A brief history of function volatility in PostgreSQL<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Function volatility was originally introduced to PostgreSQL back in <a href=\"https:\/\/www.postgresql.org\/docs\/7.0\/release.htm\" target=\"_blank\" rel=\"noreferrer noopener\">version 7<\/a>, but it wasn&#8217;t really &#8216;enforced&#8217; until version 8. So, it&#8217;s been around a while now &#8211; at the time of publication in November 2026, <a href=\"https:\/\/www.postgresql.org\/docs\/release\/19.0\/\" target=\"_blank\" rel=\"noreferrer noopener\">version 19<\/a> is the latest!<\/p>\n\n<\/div>\n<\/div> \n\n\n<p class=\"wp-block-paragraph\"><strong>There are<\/strong> <strong>three PostgreSQL function volatility levels<\/strong>: <code><strong>VOLATILE<\/strong><\/code>, <code><strong>STABLE<\/strong><\/code>, and <code><strong>IMMUTABLE<\/strong><\/code>. <strong>The default is <code>VOLATILE<\/code>.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here\u2019s how the three levels compare.<\/p>\n\n\n\n<h2 id=\"h-the-three-function-volatility-levels-in-postgresql-explained\" class=\"wp-block-heading\">The three function volatility levels in PostgreSQL explained<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Level<\/th><th>Can modify data?<\/th><th>Result guarantee<\/th><th>What the optimizer can do<\/th><th>Usable in an index expression?<\/th><th>Examples<\/th><\/tr><\/thead><tbody><tr><td><strong><code>VOLATILE<\/code><\/strong> (default)<\/td><td>Yes<\/td><td>None; can change on every call<\/td><td>Must re-run the function for every reference or row<\/td><td>No<\/td><td><code>RANDOM()<\/code>, <code>TIMEOFDAY()<\/code><\/td><\/tr><tr><td><strong><code>STABLE<\/code><\/strong><\/td><td>No<\/td><td>Same result for the same inputs within a single statement<\/td><td>Can run once and reuse the result<\/td><td>No<\/td><td><code>CURRENT_TIMESTAMP<\/code>, <code>NOW()<\/code><\/td><\/tr><tr><td><strong><code>IMMUTABLE<\/code><\/strong><\/td><td>No<\/td><td>Same result for the same inputs, forever<\/td><td>Can fold the call into a constant<\/td><td>Yes<\/td><td><code>ABS()<\/code>, <code>LOWER()<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 id=\"h-what-does-volatile-mean-in-postgresql\" class=\"wp-block-heading\">What does <code>VOLATILE<\/code> mean in PostgreSQL?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The lowest level of volatility is the default one: <code>VOLATILE<\/code>. A<\/strong> <strong><code>VOLATILE<\/code> function can do pretty much anything with the data, up to (and including) <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/validation-verification-modification\/\" target=\"_blank\" rel=\"noreferrer noopener\">data modification<\/a>.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because of this, the optimizer can\u2019t really assume anything about the function, so must reevaluate the function each time it\u2019s referenced across any number of rows and actions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Simply put, there\u2019s no way to be sure, for a given call to the function, just what it may do. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Even if the code within a function is just a <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/the-basic-t-sql-select-statement\/\" target=\"_blank\" rel=\"noreferrer noopener\"><code>SELECT<\/code> statement<\/a>, for example, certain functions can change the values returned as the query they\u2019re used in executes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Case in point: the <code>TIMEOFDAY<\/code> function gets updated throughout the execution of a query, so its value could be different on <em>every row<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">On the other hand, the value of the <code>CURRENT_TIMESTAMP<\/code> function will be the same for <em>all<\/em> rows in a given query.<\/p>\n\n\n\n<h3 id=\"h-what-does-stable-mean-in-postgresql\" class=\"wp-block-heading\">What does <code>STABLE<\/code> mean in PostgreSQL?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>In order to be labeled as <code>STABLE<\/code>, the function cannot be changing data within the database.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Any code within the function (or even calls to other functions that manipulate the data in the database), will turn this from a <code>STABLE<\/code> function into one that should be labeled <code>VOLATILE<\/code>. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>(We\u2019ll save a discussion for using the label, or just the default, for later on in this guide.)<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Additionally, the values for all the rows within the statements in the function must not change for a given set of inputs. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Functions such as <code>TIMEOFDAY<\/code> or <code>RANDOM<\/code> return different results, which makes any query using them <code>VOLATILE<\/code>. 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\u2019s no longer <code>STABLE<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Only once you know that data will <em>always<\/em> be the same for the query\/queries involved, can you label it a <code>STABLE<\/code> function.<\/p>\n\n\n\n<h4 id=\"h-stable-in-practice-how-the-optimizer-reuses-results\" class=\"wp-block-heading\"><code>STABLE<\/code> in practice: how the optimizer reuses results<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">If the <code>STABLE<\/code> function was going to be called as part of the <code>SELECT<\/code> statement of a query, but the values passed are all the same, then the optimizer can reference this function a single time. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It&#8217;ll then get the value returned, and <em>never<\/em> execute it again within the query and transaction in question, within that statement.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">And what about indexing? Well, if you create an index that uses a function, that function must be labeled as <code>STABLE<\/code> in order to be used within the index.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The key thing to remember about <code>STABLE<\/code>: when I say the data can\u2019t change, that&#8217;s only within a given execution context. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It&#8217;s not saying that <em>&#8220;running the function now returns three rows&#8221;<\/em> or <em>&#8220;if I run the function tomorrow, it returns five rows, because the data is changed.&#8221;<\/em> <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That&#8217;s still a <code>STABLE<\/code> 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?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If not, the function is safe to mark as <code>STABLE<\/code>.<\/p>\n\n\n\n<section id=\"my-first-block-block_1a38ad83efb5d1c66a2858963e0033fb\" class=\"my-first-block alignwide\">\n    <div class=\"bg-brand-600 text-base-white py-5xl px-4xl rounded-sm bg-gradient-to-r from-brand-600 to-brand-500 red\">\n        <div class=\"gap-4xl items-start md:items-center flex flex-col md:flex-row justify-between\">\n            <div class=\"flex-1 col-span-10 lg:col-span-7\">\n                <h3 class=\"mt-0 font-display mb-2 text-display-sm\">Get started with PostgreSQL &#8211; free book download<\/h3>\n                <div class=\"child:last-of-type:mb-0\">\n                                            &#8216;Introduction to PostgreSQL for the data professional&#8217;, written by Grant Fritchey and Ryan Booz, covers all the basics of how to get started with PostgreSQL.                                    <\/div>\n            <\/div>\n                                            <a href=\"https:\/\/www.red-gate.com\/hub\/books\/introduction-to-postgresql-for-the-data-professional\/\" class=\"btn btn--secondary btn--lg\" aria-label=\"Download your free copy: Get started with PostgreSQL - free book download\">Download your free copy<\/a>\n                    <\/div>\n    <\/div>\n<\/section>\n\n\n<h2 id=\"h-what-does-immutable-mean-in-postgresql\" class=\"wp-block-heading\">What does <code>IMMUTABLE<\/code> mean in PostgreSQL?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">There&#8217;s only one real difference between the <code>STABLE<\/code> and <code>IMMUTABLE<\/code> levels of function volatility in PostgreSQL: neither can be marked on a function that manipulates data. After that, there&#8217;s a big difference between them. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>With <code>STABLE<\/code>, the results are simply the same for a given input. <\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>With <code>IMMUTABLE<\/code>, they&#8217;re the same <em>forever<\/em>. <\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Put simply &#8211; <strong>if you can\u2019t always guarantee identical results, don\u2019t label a function <code>IMMUTABLE<\/code> in<\/strong> <strong>PostgreSQL!<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In fact, <code>IMMUTABLE<\/code> should probably be saved for those few functions that return results that are either unchanging within your database, or changing extremely slowly &#8211; slow enough that multiple references within a given execution context will <em>always<\/em> return an identical value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Marking a function as <code>IMMUTABLE<\/code> basically means the optimizer will likely fold the execution of the function into a constant for use in the rest of the explain plan.<\/p>\n\n\n\n<h2 id=\"h-function-volatility-in-action-a-52-second-query-down-to-1-7ms\" class=\"wp-block-heading\">Function volatility in action: a 52-second query down to 1.7ms<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">I\u2019ve got a very contrived example of function volatility in PostgreSQL as I want you to see just how radical the difference in behavior is.<\/p>\n\n\n\n<h3 id=\"h-the-example-function-and-query\" class=\"wp-block-heading\">The example function and query<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For the example, I\u2019ve got a simple little database &#8211; one previously used in my Fun With Radios presentation. Here, I\u2019ve artificially inflated the amount of data in the <code>location_info<\/code> table to close to 600 million rows. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">And I\u2019ve got a function &#8211; <code>find_nearest_location<\/code> &#8211; that looks like this:<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \">CREATE OR REPLACE\nFUNCTION reports.find_nearest_location(p_lat NUMERIC,\np_lon NUMERIC,\np_radius_km NUMERIC DEFAULT 5.0)\n RETURNS bigint\n LANGUAGE plpgsql\n--STABLE\nAS $$\nDECLARE\n    v_location_id bigint;\n\tv_point geography;\n\nBEGIN\n    v_point := ST_SetSRID(ST_MakePoint(p_lon, p_lat), 4326);\n\n\t-- Find the nearest location within radius\n    SELECT\n\t\tll.location_id\n\tINTO\n\t\tv_location_id\n\tFROM\n\t\treports.location_lookup AS ll\n\tWHERE\n\t\tST_DWithin(ll.center_point, v_point, p_radius_km * 1000)\n\tORDER BY\n\t\tST_Distance(ll.center_point, v_point)\n\tLIMIT 1;\n\n\tRETURN v_location_id;\nEND;\n$$;<\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The important thing to note is that <code>STABLE<\/code> is currently commented <em>out<\/em> &#8211; so, when this function is created, it defaults to <code>VOLATILE<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I\u2019m going to use the function in this query:<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \">SELECT COUNT(*)\nFROM reports.location_info\nWHERE location_info_id = reports.find_nearest_location(42.0, -71.5, 5.0);<\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">When I run this query, it takes <strong>about 52 seconds<\/strong> to execute. Here&#8217;s the explain plan:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"927\" height=\"216\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2026\/10\/image-9.png\" alt=\"Explain plan (ANALYZE, BUFFERS) for the VOLATILE version of the query, showing roughly 52 seconds execution time and 8,000,062 buffers\" class=\"wp-image-113633\" srcset=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2026\/10\/image-9.png 927w, https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2026\/10\/image-9-300x70.png 300w, https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2026\/10\/image-9-768x179.png 768w\" sizes=\"auto, (max-width: 927px) 100vw, 927px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">I used both <code>ANALYZE<\/code> and <code>BUFFERS<\/code> to get a complete set of data. Before we talk about what this query is up to, though, let\u2019s change the rules. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I\u2019m going to remove the comment markers from <code>STABLE<\/code> and rebuild the query. Doing so results in <em>this<\/em> explain plan:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"867\" height=\"174\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2026\/10\/image-10.png\" alt=\"Explain plan for the STABLE version of the query, showing 1.696 ms execution time and 4 buffers\" class=\"wp-image-113634\" srcset=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2026\/10\/image-10.png 867w, https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2026\/10\/image-10-300x60.png 300w, https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2026\/10\/image-10-768x154.png 768w\" sizes=\"auto, (max-width: 867px) 100vw, 867px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">First thing that ought to jump out at you is that the <strong>execution time is 1.696 milliseconds<\/strong>. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That&#8217;s right &#8211; <strong>from about 52 seconds to 1.696 milliseconds<\/strong>. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I\u2019d say that\u2019s a win, but how is it possible?<\/p>\n\n\n\n<h3 id=\"h-why-stable-is-so-much-faster-than-volatile\" class=\"wp-block-heading\">Why <code>STABLE<\/code> is so much faster than <code>VOLATILE<\/code><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Remember <code>STABLE<\/code> says that, for a given input, we\u2019re going to have the same output &#8211; however, <code>VOLATILE<\/code> doesn\u2019t know what the output will be. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the first query (<code>VOLATILE<\/code>), it executes the function every time to validate the rows. <code>STABLE<\/code>, on the other hand, executes the function in the second query just once &#8211; and then reuses the value to retrieve exactly what\u2019s needed. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That reduces the buffers all the way down <strong>from 8,000,062 to just 4!<\/strong> In short: a single lookup on the index.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As I said, it&#8217;s a contrived example, but one that illustrates the benefits really clearly. If your functions meet the criteria for <code>STABLE<\/code>, I\u2019d sure recommend using that. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">And if your function meets the criteria for <code>IMMUTABLE<\/code>? Sure, use that too.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Ultimately, these options give the optimizer superior choices in how it\u2019s going to resolve your query. Those choices can result in radical improvements in performance.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A couple more points about the behavior. To reiterate, if you label something that&#8217;s <code>VOLATILE<\/code> as <code>STABLE<\/code>, you could see <em>radically<\/em> different results coming back from the query &#8211; and you won\u2019t get a warning or error from PostgreSQL. It\u2019ll just execute your poorly-labeled code.<\/p>\n\n\n\n<h3 id=\"h-how-to-check-function-volatility-in-your-postgresql-database\" class=\"wp-block-heading\">How to check function volatility in your PostgreSQL database<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to see a listing of functions within your database and what they have their volatility set to, you can use this:<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \">SELECT\n\tns.nspname AS schema_name,\n\tp.proname AS function_name,\n\tp.provolatile AS volatility\nFROM\n\tpg_proc AS p\nJOIN pg_namespace AS ns ON\n\tns.oid = p.pronamespace\nWHERE\n\tp.prokind = 'f'\n\tAND ns.nspname NOT IN ('pg_catalog', 'information_schema')\n\tAND ns.nspname NOT LIKE 'pg\\_toast%'\n\tAND NOT EXISTS (\n\tSELECT\n\t\t1\n\tFROM\n\t\tpg_depend d\n\tWHERE\n\t\td.objid = p.oid\n\t\tAND d.deptype = 'e'\n  );<\/pre><\/div>\n\n\n\n<h2 id=\"h-best-practice-always-label-function-volatility-in-postgresql\" class=\"wp-block-heading\">Best practice: always label function volatility in PostgreSQL<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <a href=\"https:\/\/www.postgresql.org\/docs\/current\/xfunc-volatility.html\" target=\"_blank\" rel=\"noreferrer noopener\">official PostgreSQL documentation on function volatility<\/a> is extremely clear:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>For best optimization results, you should <strong>label your functions with the strictest volatility category that is valid for them<\/strong>.<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then there&#8217;s the AWS blog with its <a href=\"https:\/\/aws.amazon.com\/blogs\/database\/volatility-classification-in-postgresql\/\" target=\"_blank\" rel=\"noreferrer noopener\">nice, long, article<\/a> on exactly <em>why<\/em> you should be using function classification, including:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>By labeling functions as <code>IMMUTABLE<\/code>, <code>STABLE<\/code>, or <code>VOLATILE<\/code>, you help the query planner optimize performance by determining when results can be cached and reused or recalculated.<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There&#8217;s also an article on <a href=\"https:\/\/techcommunity.microsoft.com\/blog\/adforpostgresql\/postgresql-query-performance-a-guide-to-function-optimization\/4386349\" target=\"_blank\" rel=\"noreferrer noopener\">performance enhancements for functions on Azure<\/a> that says:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>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.<\/em><\/p>\n\n\n\n<h3 id=\"h-why-you-should-label-every-postgresql-function\" class=\"wp-block-heading\">Why you should label every PostgreSQL function<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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: <strong>you should label your functions in PostgreSQL with their volatility<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Heck, my own sample code doesn&#8217;t even have them either! The point remains, though: <strong>label your functions<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Even if a function is <code>VOLATILE<\/code>, label it anyway. I know it&#8217;s the default, but an explicit label tells the next reader <em>\u201cI intended this one to be <code>VOLATILE<\/code>\u201d<\/em> rather than just, <em>\u201cI forgot.\u201d<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Clarity and intent matter <em>so much<\/em> in code. Accurate labels can also bring real performance benefits, because marking a function <code>STABLE<\/code> or <code>IMMUTABLE<\/code> where appropriate gives the planner room to optimize. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">But, even regardless of that &#8211; <strong>label your functions in PostgreSQL!<\/strong><\/p>\n\n\n\n<h2 id=\"h-conclusion-label-every-function\" class=\"wp-block-heading\">Conclusion: label every function<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In a conclusion you\u2019re not supposed to introduce new topics. However, I\u2019ll also mention that there\u2019s <a href=\"https:\/\/www.postgresql.org\/docs\/current\/parallel-safety.html#PARALLEL-LABELING\" target=\"_blank\" rel=\"noreferrer noopener\">labels for parallelism<\/a> as well as volatility: <code>PARALLEL SAFE<\/code>, <code>PARALLEL RESTRICTED<\/code>, and <code>PARALLEL UNSAFE<\/code>. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You might want to <a href=\"https:\/\/www.postgresql.org\/docs\/current\/parallel-safety.html#PARALLEL-LABELING\" target=\"_blank\" rel=\"noreferrer noopener\">look them up<\/a> and decide how it fits in your code as well.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As you can see, volatility labeling is important, but we&#8217;re not (yet) too great at ensuring it&#8217;s a fundamental aspect of all our code. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Going forward, I\u2019m going to change that (for obvious reasons) &#8211; 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.<\/p>\n\n\n\n<section id=\"my-first-block-block_040b975ea22f92c9ab838dcc31028b73\" class=\"my-first-block alignwide\">\n    <div class=\"bg-brand-600 text-base-white py-5xl px-4xl rounded-sm bg-gradient-to-r from-brand-600 to-brand-500 red\">\n        <div class=\"gap-4xl items-start md:items-center flex flex-col md:flex-row justify-between\">\n            <div class=\"flex-1 col-span-10 lg:col-span-7\">\n                <h3 class=\"mt-0 font-display mb-2 text-display-sm\">Free desktop tool for fast PostgreSQL monitoring and diagnostics<\/h3>\n                <div class=\"child:last-of-type:mb-0\">\n                                            Stay in control of PostgreSQL performance with Redgate pgNow \u2013 a free desktop tool for fast, focused diagnostics. No agents, no setup, just actionable insights when you need them.                                    <\/div>\n            <\/div>\n                                            <a href=\"https:\/\/www.red-gate.com\/products\/redgate-pgnow\/\" class=\"btn btn--secondary btn--lg\" aria-label=\"Learn more &amp; download now: Free desktop tool for fast PostgreSQL monitoring and diagnostics\">Learn more &amp; download now<\/a>\n                    <\/div>\n    <\/div>\n<\/section>\n\n\n<section id=\"faq\" class=\"faq-block my-5xl\">\n    <h2>FAQs<\/h2>\n\n            <h3 class=\"mt-4xl\">1. What is the default volatility of a PostgreSQL function?<\/h3>\n        <div class=\"faq-answer\">\n            <p dir=\"ltr\">A PostgreSQL function is <code>VOLATILE<\/code> by default if you don\u2019t specify a label. <code>VOLATILE<\/code> 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\u2019s referenced. Adding <code>STABLE<\/code> or <code>IMMUTABLE<\/code>, where valid, lets PostgreSQL optimize more aggressively.<\/p>\n        <\/div>\n            <h3 class=\"mt-4xl\">2. What is the difference between STABLE and IMMUTABLE in PostgreSQL?<\/h3>\n        <div class=\"faq-answer\">\n            <p dir=\"ltr\">Neither can modify data, but they differ in how long results stay the same. A <code>STABLE<\/code> function returns the same result for the same inputs within a single query execution. An <code>IMMUTABLE<\/code> function returns the same result for the same inputs forever, which lets the optimizer fold the call into a constant.<\/p>\n        <\/div>\n            <h3 class=\"mt-4xl\">3. Can I use a STABLE function in an index?<\/h3>\n        <div class=\"faq-answer\">\n            <p dir=\"ltr\">No. Functions used in an index expression must be <code>IMMUTABLE<\/code>. An index stores computed values, which would become wrong if the function\u2019s result could change. A <code>STABLE<\/code> function works fine in a query\u2019s <code>WHERE<\/code> clause, but PostgreSQL rejects it in an index definition.<\/p>\n        <\/div>\n            <h3 class=\"mt-4xl\">4. What happens if I label a function with the wrong volatility?<\/h3>\n        <div class=\"faq-answer\">\n            <p dir=\"ltr\">PostgreSQL doesn\u2019t check that the label matches what the code does, and it won\u2019t warn you. If you mark a <code>VOLATILE<\/code> function as <code>STABLE<\/code> or <code>IMMUTABLE<\/code>, 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.<\/p>\n        <\/div>\n            <h3 class=\"mt-4xl\">5. How do I check the volatility of my PostgreSQL functions?<\/h3>\n        <div class=\"faq-answer\">\n            <p dir=\"ltr\">Query the <code>pg_proc<\/code> system catalog and read the<code> provolatile<\/code> column: <code>v<\/code> means <code>VOLATILE<\/code>, <code>s<\/code> means <code>STABLE<\/code>, and <code>i<\/code> means <code>IMMUTABLE<\/code>. Join to <code>pg_namespace<\/code> 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.<\/p>\n        <\/div>\n    <\/section>\n","protected":false},"excerpt":{"rendered":"<p>Learn what VOLATILE, STABLE and IMMUTABLE mean in PostgreSQL, when to use each, and how one label cut a query from 52 seconds to 1.7ms. With explain plans.&hellip;<\/p>\n","protected":false},"author":221792,"featured_media":113061,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143523,53,143534],"tags":[4168,4170,158977,158978],"coauthors":[6785],"class_list":["post-113631","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-databases","category-featured","category-postgresql","tag-database","tag-database-administration","tag-learningpostgresqlwithgrant","tag-postgresql"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/113631","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/221792"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=113631"}],"version-history":[{"count":14,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/113631\/revisions"}],"predecessor-version":[{"id":113826,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/113631\/revisions\/113826"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media\/113061"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=113631"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=113631"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=113631"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=113631"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}