Databases 2 min read

Understanding PostgreSQL Prepared Statements and Plan Caching (Generic vs Custom)

This article explains how PostgreSQL's prepared statements cache execution plans, describing the default behavior of generating custom plans for the first five executions before switching to a generic plan, and shows how PostgreSQL 14 adds generic_plans and custom_plans columns to the pg_prepared_statements view for monitoring.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Understanding PostgreSQL Prepared Statements and Plan Caching (Generic vs Custom)

PostgreSQL's PREPARE statement can be used to cache query execution plans, reducing the number of times a plan needs to be generated.

By default, the first five executions of a prepared statement use a custom plan; subsequent executions switch to a generic plan.

In PostgreSQL 14, the pg_prepared_statements view adds two columns, generic_plans and custom_plans , to track how many times each type of plan has been used.

Example of creating and executing a prepared statement:

bill@bill=> PREPARE pr1 AS SELECT * FROM pg_class WHERE relname = $1;
bill@bill=> EXECUTE pr1('t1');
bill@bill=> SELECT * FROM pg_prepared_statements;

After several executions, the view shows the counts of generic and custom plans:

name | statement | prepare_time | parameter_types | from_sql | generic_plans | custom_plans
-----+-----------+--------------+-----------------+----------+--------------+------------
pr1  | PREPARE pr1 AS SELECT * FROM pg_class WHERE relname = $1; | 2021-05-13 10:17:28.429238+08 | {name} | t | 2 | 5
PostgreSQLDatabase Performanceprepared statementsCustom PlanGeneric PlanPlan Caching
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.