SQL function can get called twice per RPC call, depending on Prefer: count parameter #2163
-
Environment
Description of issueWe noticed that when calling one of our heavy-duty functions via rpc/, the request was taking twice as much time as expected. We traced down the issue to the constructed query not using CTE:
We managed to circumvent the issue by using Prefer: count=exact (or estimated), which would both result in the following more optimized query (using CTE):
the key being the addition of the It is not very intuitive that tweaking a count parameter would result in a better optimized query for an RPC call. In the end, the cause of the duplicated function call (at least in our case) seems to be the Is there any more straightforward way than using this count parameter to ensure that functions are only ran once via RPC? Or does it make sense to provide an option to produce a simplified query without pg_catalog.count for RPC? Thanks for a great tool! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
The problem here is not the query, but the planner not knowing that the function you are calling is costly. It assumes it is cheap enough to "optimize" the query by inlining the CTE. For such a function you can play with the
Set this to something higher than 100 and see how that affects your query execution. |
Beta Was this translation helpful? Give feedback.
-
I also remember a similar issue where a function was called many times: #1378 (comment). (Related PostgREST/postgrest-docs#255)
Additionally, if the function is VOLATILE, try changing it to STABLE or IMMUTABLE. |
Beta Was this translation helpful? Give feedback.
The problem here is not the query, but the planner not knowing that the function you are calling is costly. It assumes it is cheap enough to "optimize" the query by inlining the CTE.
For such a function you can play with the
COST
parameter inCREATE FUNCTION
: