> ## Documentation Index
> Fetch the complete documentation index at: /documents/llms.txt
> Use this file to discover all available pages before exploring further.

# Prepared statements

> From v3.2 onwards, the database provides prepared statements for executing SQL statements multiple times with the same structure but different variables.

From v3.2 onwards, the database 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:

1. **Preparation**: Users prepare a SQL statement where variables are represented by placeholders `?`. The FE parses the SQL statement and generates an execution plan.
2. **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, the database 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, the database 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:**

```SQL theme={null}
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 the `SELECT` statement** is supported.

**Example:**

Prepare a `SELECT` statement with specific values represented by placeholders `?`.

```SQL theme={null}
PREPARE select_by_id_stmt FROM 'SELECT * FROM users WHERE id = ?';
```

### SET

**Syntax:**

```SQL theme={null}
SET @var_name = expr [, ...];
```

**Parameters:**

* `var_name`: the name of a user-defined variable.
* `expr`: a user-defined variable.

**Example:** Declare variables.

```SQL theme={null}
SET @id1 = 1, @id2 = 2;
```

For more information, see [user-defined variables](/documents/4.2/sql-reference/user_defined_variables.md).

### EXECUTE

**Syntax:**

```SQL theme={null}
EXECUTE <stmt_name> [USING @var_name [, @var_name] ...]
```

**Parameters:**

* `var_name`: the name of a variable declared in the `SET` statement.
* `stmt_name`: the name of the prepared statement.

**Example:**

Pass variables to a `SELECT` statement and execute that statement.

```SQL theme={null}
EXECUTE select_by_id_stmt USING @id1;
```

### DROP PREPARE or DEALLOCATE PREPARE

**Syntax:**

```SQL theme={null}
{DEALLOCATE | DROP} PREPARE <stmt_name>
```

**Parameters:**

* `stmt_name`: The name of the prepared statement.

**Example:**

Delete a prepared statement.

```SQL theme={null}
DROP PREPARE select_by_id_stmt;
```

## Execution plan caching

The database can reuse the execution plan of a prepared statement across `EXECUTE` calls, rebinding only the parameter values instead of planning the query again. Two query shapes are eligible:

* A primary-key point query, which is cached whenever `enable_prepare_stmt` is on.
* A single-vector ANN Top-N search, which is cached only when `enable_vector_prepared_plan_cache` is also on. The query must read one table, select column references and one `approx_*` distance call, filter with `AND`-connected `column = ?` equalities, order by that distance call, and use a constant `LIMIT`.

A query is not cached when it uses `OR`, `IN`, range or `NOT` predicates, a subquery or CTE, aggregation, `DISTINCT`, a window function, `HAVING`, `INTO OUTFILE`, or a query hint, when a parameter appears anywhere other than the positions listed above, when the plan turns out to read a synchronous materialized view instead of the base table, when the plan ends up with two scans, such as the union rewrite that reads a partially refreshed materialized view alongside the base table, when the plan uses the low-cardinality string dictionary optimization, or when the table is a shared-data (cloud-native) table.

A cached plan is discarded when any of the following happens:

* Any `SET` statement runs in the session, whether or not the variable affects planning.
* The table's schema changes, or the table is dropped, renamed, or recreated.
* A row-access or column-masking policy applies to the table. The plan is not cached while a policy is in force, and because `PREPARE` keeps its analyzed statement, the statement must be prepared again after the policy is revoked before it becomes eligible again.
* The current user or active roles change.

`EXECUTE ... USING @variable` over the text protocol is never served from the cache, because its parameters are user variables rather than prepared parameters.

The `prepared_plan_cache_hit` and `prepared_plan_cache_miss` metrics report how often the cache is used.

## Examples

### Use prepared statements

The following example demonstrates how to use prepared statements to insert, delete, update, and query data from a table:

Assuming the following database named `demo` and table named `users` are already created:

```SQL theme={null}
CREATE DATABASE IF NOT EXISTS demo;
USE demo;
CREATE TABLE users (
  id BIGINT NOT NULL,
  country STRING,
  city STRING,
  revenue BIGINT
)
PRIMARY KEY (id)
DISTRIBUTED BY HASH(id);
```

1. Prepare statements for execution.

   ```SQL theme={null}
   PREPARE select_all_stmt FROM 'SELECT * FROM users';
   PREPARE select_by_id_stmt FROM 'SELECT * FROM users WHERE id = ?';
   ```

2. Declare variables in these statements.

   ```SQL theme={null}
   SET @id1 = 1, @id2 = 2;
   ```

3. Use the declared variables to execute the statements.

   ```SQL theme={null}
   -- Query all data from the table.
   EXECUTE select_all_stmt;

   -- Query data with ID 1 or 2 separately.
   EXECUTE select_by_id_stmt USING @id1;
   EXECUTE select_by_id_stmt USING @id2;
   ```

### Using Prepared Statements in Java application

The following example demonstrates how a Java application can use a JDBC driver to insert, delete, update, and query data from a table:

1. When specifying the database' connection URL in JDBC, you need to enable server-side prepared statements:

   ```Plaintext theme={null}
   jdbc:mysql://<fe_ip>:<fe_query_port>/useServerPrepStmts=true
   ```

2. The StarRocks GitHub project provides a [Java code example](https://github.com/StarRocks/starrocks/blob/main/fe/fe-core/src/test/java/com/starrocks/analysis/PreparedStmtTest.java) that explains how to insert, delete, update, and query data from a table through a JDBC driver.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.