Prepared statements: PREPARE, EXECUTE, DEALLOCATE
A prepared statement is an SQL statement that is compiled once and then run as often as needed, with different values bound to its ? placeholders. Applications normally prepare statements through their driver (for example PreparedStatement in JDBC or prepare() in the PHP, Python, Node.js and ADO.NET drivers). The same can be done in SQL with three statements:
PREPARE stmt_name FROM 'preparable_stmt'EXECUTE stmt_name [USING value [, value] ...]{DEALLOCATE | DROP} PREPARE stmt_namePREPARE
Section titled “PREPARE”PREPARE stmt_name FROM 'preparable_stmt'- stmt_name: the name used to run or drop the statement later. If a prepared statement with this name already exists in the session, it is replaced. If preparing fails, any existing statement with that name is dropped as well.
- preparable_stmt: exactly one SQL statement, as a string. Use
?(without quotes) for each value to bind at execution time.
Prepare a product search with two parameters, a minimum price and a row count:
PREPARE by_price FROM 'SELECT id, name, unit_price FROM product WHERE unit_price > ? ORDER BY unit_price DESC LIMIT ?';Prepared statements belong to the session: they live until you drop them or the connection ends. The session also keeps your user-defined variables, the last generated AUTO_INCREMENT value (LAST_INSERT_ID) and the row count of the last statement (ROW_COUNT). An idle session expires after session_state_timeout seconds (see Other parameters).
EXECUTE
Section titled “EXECUTE”EXECUTE stmt_name [USING value [, value] ...]- stmt_name: the prepared statement to run. An error is returned if it does not exist.
- value: the values for the
?placeholders, in order. The number of values must match the number of placeholders. A value can be a literal or a user-defined variable.
EXECUTE by_price USING 90, 3;| id | name | unit_price |
|---|---|---|
| 38 | Côte de Blaye | 263.50 |
| 29 | Thüringer Rostbratwurst | 123.79 |
| 454 | Lando Gym Jacket | 99.00 |
The same statement with values taken from user-defined variables:
SET @min_price = 120, @max_rows = 2;EXECUTE by_price USING @min_price, @max_rows;| id | name | unit_price |
|---|---|---|
| 38 | Côte de Blaye | 263.50 |
| 29 | Thüringer Rostbratwurst | 123.79 |
The type of a placeholder is decided by how it is used and by the value you bind. When two string values are bound to ? + ?, + concatenates them:
PREPARE st FROM 'SELECT ? + ?';EXECUTE st USING 'a', 'b';abDEALLOCATE PREPARE / DROP PREPARE
Section titled “DEALLOCATE PREPARE / DROP PREPARE”{DEALLOCATE | DROP} PREPARE stmt_nameBoth forms drop a prepared statement and free its memory on the server. Statements that are not dropped explicitly are dropped when the session ends.
DEALLOCATE PREPARE by_price;DROP PREPARE st;See also
Section titled “See also”- SET: user-defined variables
- Drivers & APIs