Prepared statements
From v3.2 onwards, StarRocks provides prepared statements for executing SQL statements multiple times with the same structure but different variables. This feature significantly improves execution efficiency and prevents SQL injection.
Description
The prepared statements basically work as follows:
- Preparation: Users prepare a SQL statement where variables are represented by placeholders
?
. The FE parses the SQL statement and generates an execution plan. - Execution: After declaring variables, users pass these variables to the statement and execute the statement. Users can execute the same statement multiple times with different variables.
Benefits
- Saves overhead of parsing: In real-world business scenarios, an application often executes a statement multiple times with the same structure but different variables. With prepared statements supported, StarRocks needs to parse the statement only once during the preparation phase. Subsequent executions of the same statement with different variables can directly use the pre-generated parsing result. As such, statement execution performance is significantly improved, especially for complex queries.
- Prevents SQL injection attacks: By separating the statement from the variables and passing user-input data as parameters rather than directly concatenating the variables into the statement, StarRocks can prevent malicious users from executing malicious SQL codes.
Usages
Prepared statements are effective only in the current session and cannot be used in other sessions. After the current session exits, the prepared statements created in that session are automatically dropped.
Syntax
The execution of a prepared statement consists of the following phases:
- PREPARE: Prepare the statement where variables are represented by placeholders
?
. - SET: Declare variables within the statement.
- EXECUTE: Pass the declared variables to the statement and execute it.
- DROP PREPARE or DEALLOCATE PREPARE: Delete the prepared statement.
PREPARE
Syntax:
PREPARE <stmt_name> FROM <preparable_stmt>
Parameters:
stmt_name
: the name given to the prepared statement, which is subsequently used to execute or deallocate that prepared statement. The name must be unique within a single session.preparable_stmt
: the SQL statement to be prepared, where the placeholder for variables is a question mark (?
). Currently, only theSELECT
statement is supported.
Example:
Prepare a SELECT
statement with specific values represented by placeholders ?
.
PREPARE select_by_id_stmt FROM 'SELECT * FROM users WHERE id = ?';