SQL reference (MySQL and MariaDB dialects)

PREPARE, EXECUTE and DEALLOCATE PREPARE

SQL-level prepared statements, EXECUTE IMMEDIATE (MariaDB) and the binary prepared-statement protocol used by drivers.

A prepared statement is parsed once and run many times with different parameters. Raft DB supports it in two ways: the SQL statements below, and the binary protocol (COM_STMT_PREPARE, COM_STMT_EXECUTE) that drivers such as Connector/J use.

Syntax#

SQL
PREPARE stmt_name FROM { 'statement text' | @user_variable }
EXECUTE stmt_name [USING @var [, @var] ...]
{ DEALLOCATE | DROP } PREPARE stmt_name

EXECUTE IMMEDIATE expr [USING expr [, expr] ...]          -- MariaDB

The statement text uses ? as the placeholder of a parameter.

Arguments#

NameMeaningDefault
stmt_nameName of the prepared statement in this session. A second PREPARE with the same name replaces it.none
USING @varUser variables, in order, for the ? placeholders.none
EXECUTE IMMEDIATEPrepare, run once and drop. The USING values may be expressions.none

Remarks#

  • The text is read at PREPARE. A syntax error is reported then, with MySQL's error 1064.
  • Wrong number of parameters: error 1210. Unknown name: 1243.
  • A session may hold 16,382 prepared statements (error 1461 beyond that), MySQL's default max_prepared_stmt_count.
  • Binary protocol. Placeholders are found by token (one inside a string or comment is not one). Each execution writes each value as a literal, escaped as a whole, at the placeholder's place, and runs the text as a normal statement, so a value can never change the structure of a statement. The answer of a SELECT is sent in the binary row format. COM_STMT_SEND_LONG_DATA and COM_STMT_RESET are supported. The statement is parsed again at every execution.
  • Checks: a Connector/J test program (identical to MySQL 9.7) and PREPARE and EXECUTE IMMEDIATE scripts (MariaDB 11.4).

Not supported yet#

  • Server-side cursors on prepared statements (COM_STMT_FETCH): answered with error 1235.

Examples#

Example:

SQL
PREPARE ins FROM 'INSERT INTO t VALUES (?, ?, ?)';
SET @a = 1, @b = 'one', @c = 10;
EXECUTE ins USING @a, @b, @c;

SET @sql = 'SELECT COUNT(*) AS n FROM t';
PREPARE cnt FROM @sql;
EXECUTE cnt;
DEALLOCATE PREPARE cnt;

EXECUTE IMMEDIATE 'SELECT 1 AS one';     -- MariaDB

See also#