对PostgreSQL的prepared statement的深入理解
看官方文档:
http://www.postgresql.org/docs/current/static/sql-prepare.html
PREPARE creates a prepared statement. A prepared statement is a server-side object that can be used to optimize performance. When the PREPARE statement is executed, the specified statement is parsed, analyzed, and rewritten. When an EXECUTE command is subsequently issued, the prepared statement is planned and executed. This division of labor avoids repetitive parse analysis work, while allowing the execution plan to depend on the specific parameter values supplied.
各自负责的阶段
Prepare: parse--> analyze-->rewritten Prepare负责 构造语法树,执行一次。
Execute: plan-->Execute 负责生成执行计划和执行,这个步骤每次都要执行。
Prepared statements can take parameters: values that are substituted into the statement when it is executed. When creating the prepared statement, refer to parameters by position, using $1, $2, etc. A corresponding list of parameter data types can optionally be specified. When a parameter's data type is not specified or is declared as unknown, the type is inferred from the context in which the parameter is used (if possible). When executing the statement, specify the actual values for these parameters in the EXECUTE statement. Refer to EXECUTE for more information about that.
Prepared statement 可以带参数,也可以不带参数。
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 that a single prepared statement cannot be used by multiple simultaneous database clients; however, each client can create their own prepared statement to use. Prepared statements can be manually cleaned up using the DEALLOCATE command.
Prepared statement 在PostgreSQL中是session 单位的。
a single prepared statement cannot be used by multiple simultaneous database clients
何时使用 prepared statement 比较有利:
Prepared statements 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, for example, if the query involves a join of many tables or requires the application of several rules. If the statement is relatively simple to plan and rewrite but relatively expensive to execute, the performance advantage of prepared statements will be less noticeable.
最有利的情况是:
When a single session is being used to execute a large number of similar statements.
最不利的情况是:
如果语句的 parse/analyze/rewritten 时间耗费很少,而plan和 execute 的时间耗费很大,则prepares statment 不一定有什么明显效果。