Home Explore Blog CI



postgresql

3rd chunk of `doc/src/sgml/ref/prepare.sgml`
9a2a49eb64b5b24b9eb55f864ac778b4e825b2dba9c0b32800000001000008f7
 plans and the average estimated cost of
   those plans is calculated.  Then a generic plan is created and its
   estimated cost is compared to the average custom-plan cost.  Subsequent
   executions use the generic plan if its cost is not so much higher than
   the average custom-plan cost as to make repeated replanning seem
   preferable.
  </para>

  <para>
   This heuristic can be overridden, forcing the server to use either
   generic or custom plans, by setting <varname>plan_cache_mode</varname>
   to <literal>force_generic_plan</literal>
   or <literal>force_custom_plan</literal> respectively.
   This setting is primarily useful if the generic plan's cost estimate
   is badly off for some reason, allowing it to be chosen even though
   its actual cost is much more than that of a custom plan.
  </para>

  <para>
   To examine the query plan <productname>PostgreSQL</productname> is using
   for a prepared statement, use <link linkend="sql-explain"><command>EXPLAIN</command></link>, for example
<programlisting>
EXPLAIN EXECUTE <replaceable>name</replaceable>(<replaceable>parameter_values</replaceable>);
</programlisting>
   If a generic plan is in use, it will contain parameter symbols
   <literal>$<replaceable>n</replaceable></literal>, while a custom plan
   will have the supplied parameter values substituted into it.
  </para>

  <para>
   For more information on query planning and the statistics collected
   by <productname>PostgreSQL</productname> for that purpose, see
   the <xref linkend="sql-analyze"/>
   documentation.
  </para>

  <para>
   Although the main point of a prepared statement is to avoid repeated parse
   analysis and planning of the statement, <productname>PostgreSQL</productname> will
   force re-analysis and re-planning of the statement before using it
   whenever database objects used in the statement have undergone
   definitional (DDL) changes or their planner statistics have
   been updated since the previous use of the prepared
   statement.  Also, if the value of <xref linkend="guc-search-path"/> changes
   from one use to the next, the statement will be re-parsed using the new
   <varname>search_path</varname>.  (This latter behavior is new as of
   <productname>PostgreSQL</productname> 9.3.)  These rules make use of a

Title: Prepared Statement Plan Selection and Re-analysis
Summary
The server automatically chooses between generic and custom query plans for prepared statements based on the cost of the first five executions. This heuristic can be overridden using the 'plan_cache_mode' setting. The EXPLAIN command can be used to examine the query plan. PostgreSQL will re-analyze and re-plan the statement if database objects used in the statement have undergone definitional changes or their planner statistics have been updated, or if the value of search_path changes.