1. It depends.
If you do not use prepared statements, PostgreSQL schedules the query each time again using the parameter values. It is known as a user plan.
With prepared statements (and you're right, PL / pgSQL functions use prepared statements), this is more complicated. PostgreSQL prepares the statement (parses its text and saves the parse tree), but reschedules it every time it is executed. Custom plans are generated at least 5 times. After that, the planner considers the use of a general plan (for example, independent of the parameter) if it costs less than the average cost of custom plans generated so far.
Note that the cost of the plan is an estimate of the scheduler, not the actual I / O operations or processor cycles.
So, a problem may arise, but for this you need some bad luck.
2. The approach you propose will not work, because it does not change the behavior of the function.
In general, it is not so ugly for PostgreSQL to use non-parameters (as, for example, for Oracle), because PostgreSQL does not have a common cache for plans. Prepared plans are stored in each internal memory, so rescheduling will not affect other sessions.
But, as far as I know, there is currently no way to force the scheduler to use custom plans (except for reconnecting after 5 executions ...).
source share