Query plan caching with pl/pgsql

后端 未结 1 920
暖寄归人
暖寄归人 2021-01-06 11:48

I am having troubles understanding how the query plan caching works for pl/pgsql.

I want to built all-in-one queries with JOINs and IFs, s

相关标签:
1条回答
  • 2021-01-06 12:31

    Plans for static queries (without EXECUTE) are always cached, plans for dynamic queries (with EXECUTE) cannot be cached.

    In your case, it would be impossible to use a static query anyway, because, as you quote, that would mean that you can only use a fixed set of tables in your query.

    I gather that you are confused by the discussion of the trade-offs between static and dynamic queries in the documentation.

    Definition: query parameters are values that are not part of the query string, like $1 or a PL/pgSQL variable name in a static query.

    For a static query, the procedure is as follows:

    For the first 5 executions, it will be planned using the actual parameter values (“custom plan”), and if the estimated execution time is not significantly shorter than that of a plan that ignores the actual parameter values (“generic plan”), the generic plan will be used from the sixth execution on.

    Since the generic plan is cached, that means that there is no planning cost from the sixth execution on.

    Dynamic queries are planned every time they are executed.

    The trade-off is the following: dynamic queries run up planning cost whenever they are executed, but since they are always planned with the actual parameter values, they end up with a better execution plan, which can save time during query execution.

    Now if a query is sensitive to parameter values, that means that the optimal plan will vary significantly with the parameter values, so you will usually win if you plan the query every time.

    Queries without parameters will always profit from plan caching, unless the table contents change a lot during the lifetime of a single session, so that the cached plan becomes suboptimal.

    0 讨论(0)
提交回复
热议问题