cmc-csci143 icon indicating copy to clipboard operation
cmc-csci143 copied to clipboard

Function Not Updating Properly with CREATE OR REPLACE FUNCTION Due to Plan Caching

Open RyanL-N opened this issue 9 months ago • 3 comments

CREATE OR REPLACE FUNCTION does not update execution plans for modified SQL queries inside a function unless the function is explicitly dropped first (DROP FUNCTION IF EXISTS). This happens because PL/pgSQL caches execution plans after the first execution and continues using the cached version.

Reference: PostgreSQL 41.11.2 Plan Caching

A workaround is to drop the function before recreating it to force PostgreSQL to recompile the execution plan.

RyanL-N avatar Mar 07 '25 18:03 RyanL-N

This makes sense to me that postgres would cache execution plans of PL/pgSQL functions.

In order to get the extra credit that we talked about, you'd need to: explain how/why postgres would not update a SQL function when the ORDER BY clause changes. (This is the fact that is surprising to me.)

mikeizbicki avatar Mar 07 '25 18:03 mikeizbicki

Why ORDER BY is Not Updated

  1. PostgreSQL does not reparse SQL queries inside a function after the initial execution. Instead, it reuses a cached execution plan for performance reasons.
  2. Since ORDER BY affects sorting but does not change the structure of the query, PostgreSQL considers it non-essential to recompile the execution plan.
  3. Execution plans prioritize efficiency over minor query modifications. PostgreSQL optimizes for performance by keeping an existing execution plan unless a structural change (e.g., modifying columns, joins, or filters) occurs.
  4. Even if ORDER BY is modified in the function definition, PostgreSQL still uses the previously cached plan, leading to unexpected behavior where results may not be sorted as intended.
  5. To force PostgreSQL to recognize the change, the function must be dropped and recreated (DROP FUNCTION IF EXISTS). This ensures a new execution plan is generated reflecting the updated ORDER BY clause.

RyanL-N avatar Mar 07 '25 22:03 RyanL-N

You've made a bunch of claims here, but you haven't provided any supporting evidence of those claims. For example, the link you provided opening this issue doesn't even contain the string ORDER BY anywhere, so I don't know how you are concluding "Since ORDER BY affects sorting but does not change the structure of the query". You need to provide a precise citation to the location in the documentation (both link and relevant quoted text).

mikeizbicki avatar Mar 07 '25 22:03 mikeizbicki