PREPARE Statement
Parse and optimize a SQL statement for later use. This command assigns a name to the statement, enabling efficient execution with parameters.
Syntax
PREPARE [LOCAL] stmt_name FROM preparable_stmtDescription
The PREPARE statement prepares a statement and assigns it a name,stmt_name, by which to refer to the statement later. Statement names are not case sensitive. preparable_stmt is an expression with the text of the statement. It cannot contain stored function calls or subqueries. The text must represent a single SQL statement, not multiple statements. Within the statement, ? characters can be used as parameter markers to indicate where data values are to be bound to the query later when you execute it. The ? characters should not be enclosed within quotes, even if you intend to bind them to string values. Parameter markers can be used only where expressions should appear, not for SQL keywords, identifiers, and so forth.
The scope of a prepared statement is the session within which it is created. Other sessions cannot see it.
If a prepared statement with the given name already exists, it is deallocated implicitly before the new statement is prepared. This means that if the new statement contains an error and cannot be prepared, an error is returned and no statement with the given name exists.
Prepared statements can be PREPARE and EXECUTE in a stored procedure, but never in a trigger. In a stored function they are not permitted at all before MariaDB 13.2.1, and from MariaDB 13.2.1 only in the restricted context described in Dynamic SQL in Stored Functions. Also, even if the statement is prepared with PREPARE in a procedure, it will not be deallocated when the procedure execution ends.
A prepared statement can access user-defined variables, but not local variables or procedure's parameters.
If the prepared statement contains a syntax error, PREPARE will fail. As a side effect, stored procedures can use it to check if a statement is valid. For example:
CREATE PROCEDURE `test_stmt`(IN sql_text TEXT)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SELECT CONCAT(sql_text, ' is not valid');
END;
SET @SQL := sql_text;
PREPARE stmt FROM @SQL;
DEALLOCATE PREPARE stmt;
END;The FOUND_ROWS() and ROW_COUNT() functions, if called immediately after EXECUTE, return the number of rows read or affected by the prepared statements; however, if they are called after DEALLOCATE PREPARE, they provide information about this statement. If the prepared statement produces errors or warnings, GET DIAGNOSTICS return information about them. DEALLOCATE PREPARE shouldn't clear the diagnostics area, unless it produces an error.
A prepared statement is executed with EXECUTE and released with DEALLOCATE PREPARE.
The max_prepared_stmt_count server system variable determines the number of allowed prepared statements that can be prepared on the server. If it is set to 0, prepared statements are not allowed. If the limit is reached, an error similar to the following will be produced:
Oracle Mode
In Oracle mode, PREPARE stmt FROM 'SELECT :1, :2' is used instead of ?.
LOCAL Statement Names
Inside a stored procedure, PREPARE LOCAL takes the prepared statement name from the value of a stored-procedure variable instead of from a literal identifier:
Here spvar is a local variable (or routine parameter) whose string value is used as the prepared statement name — useful when the name must be computed at runtime. LOCAL does not create a separate namespace: a statement prepared with PREPARE LOCAL can be executed or deallocated by its resolved name with a plain EXECUTE or DEALLOCATE PREPARE, and the reverse also works.
PREPARE LOCAL is only valid inside a stored procedure. Like the plain form, it is never permitted in a trigger, and in a stored function it is subject to the same restrictions as PREPARE — see Dynamic SQL in Stored Functions.
Example:
Dynamic SQL in Stored Functions
The dynamic SQL statements — PREPARE, EXECUTE, DEALLOCATE PREPARE, EXECUTE IMMEDIATE, and OPEN ... FOR PREPARE (opening a cursor over a prepared statement) — have always been rejected inside a stored function or a trigger. Before MariaDB 13.2.1 the rejection happened in the parser, so the CREATE FUNCTION itself failed.
From MariaDB 13.2.1 the parser accepts dynamic SQL in a function body, and the restriction is applied when the function is called instead. Triggers are unchanged: dynamic SQL in a trigger body is still rejected at CREATE TRIGGER time.
Where a Function Containing Dynamic SQL May Be Called
The function call must be the entire right-hand side of an assignment to a stored routine variable. Three forms qualify:
Anywhere else, the call fails with ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG:
The rejected contexts include the select list, a WHERE clause, SELECT ... INTO (whether the target is a user variable or a routine variable), an assignment to a user variable or a system variable, an argument of a CALL, an IF or WHILE condition, and a RETURN expression.
Only a bare function call is recognized. Using the function inside a larger expression, as in SET v= f1()+0, is not an assignment right-hand side and is rejected.
Opening a Cursor Over a Prepared Statement
OPEN ... FOR PREPARE sets the same internal flag as PREPARE and EXECUTE IMMEDIATE, so a function that opens a cursor over a prepared statement is subject to the same rule — permitted only when the function call is itself an assignment right-hand side, whether the statement is prepared inside the function or beforehand in the calling scope:
Further Restrictions
Statements that cause an explicit or implicit commit are still not permitted, even in an assignment right-hand side. Running DDL,
COMMIT,ROLLBACK,START TRANSACTIONorLOCK TABLESthrough dynamic SQL fails withER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG.A function may still not return a result set.
EXECUTE IMMEDIATE 'CALL p1()'wherep1()selects rows fails withER_SP_NO_RETSET.A function containing dynamic SQL is not pre-locked by its caller: it opens and locks its own tables, in the manner of a stored procedure. As a consequence, a statement that has tables of its own cannot call such a function at all —
SELECT * FROM t1 WHERE a= f1()is rejected even whenf1()touches a different table. The check applies to the statement rather than the individual function, so a second function called alongside a dynamic one is rejected with it.No metadata lock is taken on the routine itself, so a concurrent DROP FUNCTION can complete while the function is executing.
Such a function is not written to the binary log as a single
SELECT f1()call. Its statements are logged individually, as a stored procedure's are.A prepared statement created inside a function belongs to the session, not to the function. It survives the return, and a
DEALLOCATE PREPAREinside a function deallocates the session's statement.
Permitted Statements
All statements can be prepared, except PREPARE, EXECUTE, and DEALLOCATE / DROP PREPARE.
Prior to this, not all statements can be prepared. Only the following SQL commands are permitted:
FLUSH {TABLE | TABLES | TABLES WITH READ LOCK | HOSTS | PRIVILEGES | LOGS | STATUS | MASTER | SLAVE | DES_KEY_FILE | USER_RESOURCES | QUERY CACHE | TABLE_STATISTICS | INDEX_STATISTICS | USER_STATISTICS | CLIENT_STATISTICS}
RESET {MASTER | SLAVE | QUERY CACHE}
SHOW {DATABASES | TABLES | OPEN TABLES | TABLE STATUS | COLUMNS | INDEX | TRIGGERS |EVENTS | GRANTS | CHARACTER SET | COLLATION | ENGINES | [PLUGINS SONAME] | PRIVILEGES |PROCESSLIST | PROFILE | PROFILES | VARIABLES | STATUS | WARNINGS | ERRORS |TABLE_STATISTICS | INDEX_STATISTICS | USER_STATISTICS | CLIENT_STATISTICS | AUTHORS |CONTRIBUTORS}
SHOW {MASTER | BINARY} LOGS
SHOW {MASTER | SLAVE | TABLES | INNODB | FUNCTION | PROCEDURE} STATUS
UNINSTALL {PLUGIN | SONAME}
Synonyms are not listed here, but can be used. For example, DESC can be used instead of DESCRIBE.
Compound statements can be prepared too.
Note that if a statement can be run in a stored routine, it will work even if it is called by a prepared statement. For example, SIGNAL can't be directly prepared. However, it is allowed in stored routines. If the x() procedure contains SIGNAL, you can still prepare and execute the 'CALL x();' prepared statement.
PREPARE supports most kinds of expressions as well, for example:
When PREPARE is used with a statement which is not supported, the following error is produced:
Example
Since identifiers are not permitted as prepared statements parameters, sometimes it is necessary to dynamically compose an SQL statement. This technique is called dynamic SQL). The following example shows how to use dynamic SQL:
Use of variables in prepared statements:
See Also
This page is licensed: GPLv2, originally from fill_help_tables.sql
Last updated
Was this helpful?

