PREPARE(7)

πŸ“¦ version 16.15, in opensuse-leap 16.0

πŸ’… PREPARE (like, the PostgreSQL 16.15 manual, but make it make sense)

okay bestie, so this one's from the PostgreSQL 16.15 docs and it's literally all about PREPARE β€” the glow-up your queries deserve. sit down, hydrate, let's go 🫢

✨ NAME ✨

PREPARE β€” prepare a statement for execution. that's it, that's the vibe. it's giving "get ready in advance" energy πŸ’…

πŸŽ€ SYNOPSIS πŸŽ€

PREPARE name [ ( data_type [, ...] ) ] AS statement

look at her. so clean. so iconic. 🌸

πŸ¦‹ DESCRIPTION πŸ¦‹

so PREPARE creates a prepared statement. and a prepared statement is a server-side object that can be used to optimize performance β€” yes, she's a whole server-side icon, not just a random string you're passing around πŸ‘‘

when the PREPARE statement gets executed, the statement you specified is parsed, analyzed, and rewritten. then, when an EXECUTE command is subsequently issued, the prepared statement is planned and executed. this division of labor is the whole point, fr fr β€” it avoids repetitive parse analysis work, while still letting the execution plan depend on the specific parameter values you supply. slay πŸ’–

prepared statements can take parameters: values that get substituted into the statement when it's executed. when you're creating the prepared statement, you refer to parameters by position β€” $1, $2, etc. a corresponding list of parameter data types can optionally be specified, no pressure. when a parameter's data type isn't specified or is declared as unknown, the type is inferred from the context in which the parameter is first referenced (if possible). when executing the statement, you specify the actual values for these parameters in the EXECUTE statement. and yeah, go read EXECUTE(7) for more on that, iykyk.

okay important thing, don't get attached 😭 prepared statements only last for the duration of the current database session. when the session ends, the prepared statement is forgotten, so it must be recreated before being used again. this also means a single prepared statement cannot be used by multiple simultaneous database clients β€” but no worries, each client can create their own prepared statement to use. and you can manually clean them up using the DEALLOCATE command, very demure, very mindful 🧹

now, when is this whole thing actually worth it? prepared statements potentially have the largest performance advantage when a single session is being used to execute a large number of similar statements. the performance difference will be particularly significant if the statements are complex to plan or rewrite β€” like, e.g., if the query involves a join of many tables or requires the application of several rules. but if the statement is relatively simple to plan and rewrite and relatively expensive to execute, the performance advantage of prepared statements will be less noticeable. managing expectations, we love to see it πŸ’œ

πŸ“ PARAMETERS πŸ“

  • name β€” an arbitrary name given to this particular prepared statement. it must be unique within a single session, and it's subsequently used to execute or deallocate a previously prepared statement. pick something cute but, like, functional ✨
  • data_type β€” the data type of a parameter to the prepared statement. if the data type of a particular parameter is unspecified or is specified as unknown, it will be inferred from the context in which the parameter is first referenced. to refer to the parameters in the prepared statement itself, use $1, $2, etc. πŸ’…
  • statement β€” any SELECT, INSERT, UPDATE, DELETE, MERGE, or VALUES statement. that's the whole menu, bestie πŸ“

πŸ”₯ NOTES πŸ”₯

the two plans (generic vs custom) πŸ‘‘

a prepared statement can be executed with either a generic plan or a custom plan.

  • a generic plan is the same across all executions
  • a custom plan is generated for a specific execution using the parameter values given in that call

use of a generic plan avoids planning overhead, but in some situations a custom plan will be much more efficient to execute, because the planner can make use of knowledge of the parameter values. (of course, if the prepared statement has no parameters, then this is moot and a generic plan is always used. so if you're sitting there with zero params, this whole section is not about you πŸ’€)

how the server picks (the auto rule) 🧚

by default β€” that is, when plan_cache_mode is set to auto β€” the server will automatically choose whether to use a generic or custom plan for a prepared statement that has parameters. and the current rule for this is so specific, i'm obsessed:

  1. the first five executions are done with custom plans, and the average estimated cost of those plans is calculated
  2. then a generic plan is created and its estimated cost is compared to the average custom-plan cost
  3. 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

like, she's doing math in the background so you don't have to. main character energy 🌈

overriding the heuristic πŸŽ€

this heuristic can be overridden, forcing the server to use either generic or custom plans, by setting plan_cache_mode to force_generic_plan or force_custom_plan respectively.

this setting is primarily useful if the generic plan's cost estimate is badly off for some reason β€” it lets the generic plan be chosen even though its actual cost is much more than that of a custom plan. so like, use with intention, not on a whim πŸ™ˆ

peeking at the plan πŸ‘€

to examine the query plan PostgreSQL is using for a prepared statement, use EXPLAIN, for example:

EXPLAIN EXECUTE name(parameter_values);

if a generic plan is in use, it will contain parameter symbols $n, while a custom plan will have the supplied parameter values substituted into it.

for more information on query planning and the statistics collected by PostgreSQL for that purpose, see the ANALYZE(7) documentation. go read it, she's thorough πŸ’–

the re-parse rules (no cap, this part matters) ⭐

although the main point of a prepared statement is to avoid repeated parse analysis and planning of the statement, PostgreSQL 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 search_path changes from one use to the next, the statement will be re-parsed using the new search_path. (this latter behavior is new as of PostgreSQL 9.3 β€” vintage but not that vintage πŸ’…)

these rules make use of a prepared statement semantically almost equivalent to re-submitting the same query text over and over, but with a performance benefit if no object definitions are changed β€” especially if the best plan remains the same across uses.

and here's the one little "almost," bestie, so listen up: an example of a case where the semantic equivalence is not perfect is that if the statement refers to a table by an unqualified name, and then a new table of the same name is created in a schema appearing earlier in the search_path, no automatic re-parse will occur since no object used in the statement changed. however, if some other change forces a re-parse, the new table will be referenced in subsequent uses. sneaky but documented 😭

seeing everything πŸ¦‹

you can see all prepared statements available in the session by querying the pg_prepared_statements system view. it's giving receipts ✨


🌸 EXAMPLES 🌸

create a prepared statement for an INSERT statement, and then execute it:

PREPARE fooplan (int, text, bool, numeric) AS
    INSERT INTO foo VALUES($1, $2, $3, $4);
EXECUTE fooplan(1, 'Hunter Valley', 't', 200.00);

create a prepared statement for a SELECT statement, and then execute it:

PREPARE usrrptplan (int) AS
    SELECT * FROM users u, logs l WHERE u.usrid=$1 AND u.usrid=l.usrid
    AND l.date = $2;
EXECUTE usrrptplan(1, current_date);

in this example, the data type of the second parameter is not specified, so it is inferred from the context in which $2 is used. see, she pays attention πŸ‘‘

πŸ’€ COMPATIBILITY πŸ’€

the SQL standard includes a PREPARE statement, but it is only for use in embedded SQL. this version of the PREPARE statement also uses a somewhat different syntax. so like, don't assume the standard one and this one are twins, they're more like distant cousins at the same party πŸ™ˆ

πŸ‘‘ SEE ALSO πŸ‘‘

DEALLOCATE(7), EXECUTE(7)


and that's the page, bestie πŸŽ€ this was PostgreSQL 16.15, dated 2026 β€” go forth and prepare your statements, and remember: no cap, the facts above are the facts. mwah πŸ’‹βœ¨πŸ«Ά

πŸ“¦ where this page comes from