{
    "mode": "man",
    "parameter": "PREPARE",
    "section": "7",
    "url": "https://www.chedong.com/phpMan.php/man/PREPARE/7/json",
    "generated": "2026-10-04T09:21:39Z",
    "synopsis": "PREPARE name [ ( datatype [, ...] ) ] AS statement",
    "sections": {
        "NAME": {
            "content": "PREPARE - prepare a statement for execution\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "PREPARE name [ ( datatype [, ...] ) ] AS statement\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "PREPARE creates a prepared statement. A prepared statement is a server-side object that can\nbe used to optimize performance. When the PREPARE statement is executed, the specified\nstatement is parsed, analyzed, and rewritten. When an EXECUTE command is subsequently issued,\nthe prepared statement is planned and executed. This division of labor avoids repetitive\nparse analysis work, while allowing the execution plan to depend on the specific parameter\nvalues supplied.\n\nPrepared statements can take parameters: values that are substituted into the statement when\nit is executed. When creating the prepared statement, refer to parameters by position, using\n$1, $2, etc. A corresponding list of parameter data types can optionally be specified. When a\nparameter's data type is not specified or is declared as unknown, the type is inferred from\nthe context in which the parameter is first referenced (if possible). When executing the\nstatement, specify the actual values for these parameters in the EXECUTE statement. Refer to\nEXECUTE(7) for more information about that.\n\nPrepared statements only last for the duration of the current database session. When the\nsession ends, the prepared statement is forgotten, so it must be recreated before being used\nagain. This also means that a single prepared statement cannot be used by multiple\nsimultaneous database clients; however, each client can create their own prepared statement\nto use. Prepared statements can be manually cleaned up using the DEALLOCATE command.\n\nPrepared statements potentially have the largest performance advantage when a single session\nis being used to execute a large number of similar statements. The performance difference\nwill be particularly significant if the statements are complex to plan or rewrite, e.g., if\nthe query involves a join of many tables or requires the application of several rules. If the\nstatement is relatively simple to plan and rewrite but relatively expensive to execute, the\nperformance advantage of prepared statements will be less noticeable.\n",
            "subsections": []
        },
        "PARAMETERS": {
            "content": "name\nAn arbitrary name given to this particular prepared statement. It must be unique within a\nsingle session and is subsequently used to execute or deallocate a previously prepared\nstatement.\n\ndatatype\nThe data type of a parameter to the prepared statement. If the data type of a particular\nparameter is unspecified or is specified as unknown, it will be inferred from the context\nin which the parameter is first referenced. To refer to the parameters in the prepared\nstatement itself, use $1, $2, etc.\n\nstatement\nAny SELECT, INSERT, UPDATE, DELETE, MERGE, or VALUES statement.\n",
            "subsections": []
        },
        "NOTES": {
            "content": "A prepared statement can be executed with either a generic plan or a custom plan. A generic\nplan is the same across all executions, while a custom plan is generated for a specific\nexecution using the parameter values given in that call. Use of a generic plan avoids\nplanning overhead, but in some situations a custom plan will be much more efficient to\nexecute because the planner can make use of knowledge of the parameter values. (Of course, if\nthe prepared statement has no parameters, then this is moot and a generic plan is always\nused.)\n\nBy default (that is, when plancachemode is set to auto), the server will automatically\nchoose whether to use a generic or custom plan for a prepared statement that has parameters.\nThe current rule for this is that the first five executions are done with custom plans and\nthe average estimated cost of those plans is calculated. Then a generic plan is created and\nits estimated cost is compared to the average custom-plan cost. Subsequent executions use the\ngeneric plan if its cost is not so much higher than the average custom-plan cost as to make\nrepeated replanning seem preferable.\n\nThis heuristic can be overridden, forcing the server to use either generic or custom plans,\nby setting plancachemode to forcegenericplan or forcecustomplan respectively. This\nsetting is primarily useful if the generic plan's cost estimate is badly off for some reason,\nallowing it to be chosen even though its actual cost is much more than that of a custom plan.\n\nTo examine the query plan PostgreSQL is using for a prepared statement, use EXPLAIN, for\nexample\n\nEXPLAIN EXECUTE name(parametervalues);\n\nIf a generic plan is in use, it will contain parameter symbols $n, while a custom plan will\nhave the supplied parameter values substituted into it.\n\nFor more information on query planning and the statistics collected by PostgreSQL for that\npurpose, see the ANALYZE(7) documentation.\n\nAlthough the main point of a prepared statement is to avoid repeated parse analysis and\nplanning of the statement, PostgreSQL will force re-analysis and re-planning of the statement\nbefore using it whenever database objects used in the statement have undergone definitional\n(DDL) changes or their planner statistics have been updated since the previous use of the\nprepared statement. Also, if the value of searchpath changes from one use to the next, the\nstatement will be re-parsed using the new searchpath. (This latter behavior is new as of\nPostgreSQL 9.3.) These rules make use of a prepared statement semantically almost equivalent\nto re-submitting the same query text over and over, but with a performance benefit if no\nobject definitions are changed, especially if the best plan remains the same across uses. An\nexample of a case where the semantic equivalence is not perfect is that if the statement\nrefers to a table by an unqualified name, and then a new table of the same name is created in\na schema appearing earlier in the searchpath, no automatic re-parse will occur since no\nobject used in the statement changed. However, if some other change forces a re-parse, the\nnew table will be referenced in subsequent uses.\n\nYou can see all prepared statements available in the session by querying the\npgpreparedstatements system view.\n",
            "subsections": []
        },
        "EXAMPLES": {
            "content": "Create a prepared statement for an INSERT statement, and then execute it:\n\nPREPARE fooplan (int, text, bool, numeric) AS\nINSERT INTO foo VALUES($1, $2, $3, $4);\nEXECUTE fooplan(1, 'Hunter Valley', 't', 200.00);\n\nCreate a prepared statement for a SELECT statement, and then execute it:\n\nPREPARE usrrptplan (int) AS\nSELECT * FROM users u, logs l WHERE u.usrid=$1 AND u.usrid=l.usrid\nAND l.date = $2;\nEXECUTE usrrptplan(1, currentdate);\n\nIn this example, the data type of the second parameter is not specified, so it is inferred\nfrom the context in which $2 is used.\n",
            "subsections": []
        },
        "COMPATIBILITY": {
            "content": "The SQL standard includes a PREPARE statement, but it is only for use in embedded SQL. This\nversion of the PREPARE statement also uses a somewhat different syntax.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "DEALLOCATE(7), EXECUTE(7)\n\nPostgreSQL 16.14                                2026                                      PREPARE(7)",
            "subsections": []
        }
    },
    "summary": "PREPARE - prepare a statement for execution",
    "flags": [],
    "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, currentdate);",
        "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_also": [
        {
            "name": "DEALLOCATE",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/DEALLOCATE/7/json"
        },
        {
            "name": "EXECUTE",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/EXECUTE/7/json"
        }
    ]
}