PREPARE <identifier> AS <select-query>The
prepare
statement makes it possible to create a SQL statement that will be executed multiple times. Used together with theexecute
statement, this saves processor time by eliminating the statement compilation step each time the statement is executed.The
<identifier>
specifies the name of the prepared statement. Parameters in the query are represented using "?
" placeholders; for example:prepare lookup as select * from t where x=?;All parameters are assumed to have type
string
unless explicitly type cast. For example, the following statement allows substituting aninteger
value into the query string:prepare lookup as select * from t where x=?::integer;The following example statements demonstrate defining and using prepared statements:
create table t(x integer primary key, y integer); prepare lookup as select * from t where x=?::integer; prepare lookup2 as select * from t where x=?::integer and y=?::integer; insert into t values (1,10); execute lookup(1); explain execute lookup(1); execute lookup2(1,10); explain execute lookup2(1,10); prepare selfjoin as select * from t as t1 left join t as t2 on t1.y=t2.y; execute selfjoin(); explain execute selfjoin(); execute selfjoin();