Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

Besides preventing SQL injection, what performance benefits can PreparedStatement bring, and what driver settings affect them?

A PreparedStatement lets the database reuse the work of parsing and planning a statement across executions, instead of redoing it every time. The PostgreSQL driver switches to a named server-side prepared statement after a statement has run a few times on a connection (prepareThreshold, 5 by default), while MySQL Connector/J needs useServerPrepStmts and cachePrepStmts to prepare on the server and cache statements on the client. Two cautions: a reused generic plan can be worse than a custom plan for skewed data, and statement caches live per connection, so pool churn reduces their benefit.

Why this question is asked

Most of us learn PreparedStatement as the cure for SQL injection, which it is. But in a busy service the same handful of statements run millions of times a day, and the cost of preparing them again and again shows up as database CPU and latency. Interviewers ask this internals question to see whether we know what preparing actually means and which driver settings control it. In this answer, we will recap what a database does with a statement, look at PostgreSQL's prepareThreshold, look at MySQL's settings, see when plan reuse backfires, and see why connection pools matter.

1A Quick Recap: What the Database Does With a Statement

When a database receives a SQL statement, it does several steps before it touches any data. It parses the text into a tree, checks names and types against the catalog, may rewrite it, and then plans it: it decides which indexes to use, the join order and the join method. For a simple lookup, planning can take as long as executing. For a complex query with many joins, planning can take milliseconds.

Preparing a statement means doing the parse and analysis once and keeping the result on the server under a name, so later executions only send the parameter values. Depending on the database, the plan may be kept too. A PreparedStatement in JDBC is the client-side object that makes this possible; whether the driver actually prepares on the server, and when, depends on the driver's settings.

Work done per execution
StepPlain statementServer-side prepared, reused
Send SQL textevery timeonce, then only values
Parse and analyseevery timeonce per connection
Planevery timecustom per execution, or a cached generic plan
Executeevery timeevery time
Reuse removes the early steps; whether the plan is reused is a separate decision.

2PostgreSQL and prepareThreshold

The PostgreSQL driver, pgjdbc, uses the extended query protocol for every PreparedStatement, which already sends values separately from the SQL. At first it uses an unnamed statement, which the server parses for that one execution. Once the same PreparedStatement text has run prepareThreshold times on the same connection, 5 by default, the driver switches to a named server-side statement and keeps reusing it, so later executions skip parsing entirely.

Java
// jdbc:postgresql://db:5432/shop?prepareThreshold=5&preparedStatementCacheQueries=256
for (int i = 1; i <= 7; i++) {
try (PreparedStatement ps = con.prepareStatement("select name from product where id = ?")) {
ps.setLong(1, i);
ps.executeQuery();
}
}
// executions 1-4: unnamed statement, parsed each time
// execution 5 onwards: named server statement S_1, parse skipped

Notice that we closed and recreated the PreparedStatement in the loop, and it still counted. That is because pgjdbc keeps a per-connection cache of statements keyed by SQL text (preparedStatementCacheQueries, 256 entries by default, and a size limit in MiB), so prepareStatement with the same text finds the existing one. Setting prepareThreshold=0 disables server-side preparing, and a negative value forces it on the first execution; check your driver version for exact semantics.

3MySQL Connector/J Settings

MySQL Connector/J behaves differently by default. With useServerPrepStmts=false, the default, it does not prepare on the server at all: it emulates prepared statements on the client by substituting escaped values into the SQL text, and the server parses every execution. The safety against injection comes from the driver's escaping. Setting useServerPrepStmts=true makes the driver use real server-side prepared statements.

cachePrepStmts=true turns on a client-side cache so that prepareStatement with the same SQL reuses the existing statement, server-side or emulated, instead of creating a new one. prepStmtCacheSize, 25 by default, sets how many statements to cache per connection, and prepStmtCacheSqlLimit, 256 characters by default, sets the longest SQL that can be cached. Those defaults are small for most applications, so a common starting point is a few hundred entries and a limit of 2048 characters, then measuring.

Properties
# Spring Boot, MySQL
spring.datasource.url=jdbc:mysql://db:3306/shop?useServerPrepStmts=true&cachePrepStmts=true&prepStmtCacheSize=250&prepStmtCacheSqlLimit=2048

Without cachePrepStmts, server-side preparing can even be slower, because each new PreparedStatement costs an extra round trip to prepare and another to close. Notice also that these are URL properties of the driver, not settings of the pool.

4When Plan Reuse Backfires

Parsing once is almost always a win. Reusing the plan is not. A custom plan is made for the actual parameter values; a generic plan is made once for any value. For a status column where 99 percent of rows are DELIVERED and 0.1 percent are PENDING, the best plan for status = 'PENDING' uses an index, while the best plan for DELIVERED scans the table. A generic plan has to pick one.

PostgreSQL handles this with plan_cache_mode, auto by default: for a named prepared statement it makes custom plans for the first five executions, and afterwards switches to a generic plan only if its estimated cost is not much worse than the average custom plan. That usually works, but with skewed data it sometimes switches to a generic plan that is terrible for the rare values. The symptom is a query that is fast in tests and becomes slow on the sixth execution on a connection. We can confirm it with EXPLAIN on a prepared statement, and fix it per role or session with plan_cache_mode = force_custom_plan, or by restructuring the query.

5Caches Live per Connection, So Pool Churn Hurts

Server-side prepared statements belong to a database session, and the driver's statement cache belongs to a JDBC connection. A new connection starts cold: the first executions of every statement pay the full cost again. So the benefit depends on connections living long. A pool such as HikariCP with maxLifetime of 30 minutes and a stable size keeps caches warm; a pool that constantly opens and closes connections, or a service that does not pool at all, gets almost no benefit.

There is one more interaction to know. A server-side pooler such as PgBouncer in transaction mode hands each transaction to any free server connection, so a named statement prepared on one server connection may not exist on the next, which produced errors such as prepared statement S_1 does not exist. Recent PgBouncer versions (1.21 and later) can track protocol-level prepared statements with max_prepared_statements; with older versions, teams set prepareThreshold=0. Check your versions before deploying.

6Follow-up questions

Is there any performance cost to PreparedStatement?

For a statement that runs only once, a server-side prepare adds a round trip compared with sending the SQL directly, which is why pgjdbc waits for a few executions before preparing on the server and why MySQL emulates by default. For anything that repeats, the saving outweighs that. The real risk is memory: thousands of distinct statement texts, for example from SQL built with literal values, fill the caches and get no reuse.

How do we tell whether statement caching is working?

On PostgreSQL, pg_stat_statements shows how often each statement runs and the time spent planning versus executing (when planning tracking is on), and pg_prepared_statements in a session lists the statements prepared on it. On MySQL, the performance schema and the Com_stmt_prepare and Com_stmt_execute status counters show whether statements are prepared once and executed many times.

Does Hibernate benefit from this?

Yes. Hibernate generates the same SQL text for the same entity operations, and it always uses PreparedStatement, so its statements hit the driver caches well. Where it can hurt is IN lists of varying length, which produce a new SQL text per size; Hibernate's in-clause parameter padding reduces the number of variants.

7Conclusion

In this answer, we saw that preparing lets the database parse a statement once and run it many times, and that drivers control when this happens: pgjdbc switches to named server-side statements after prepareThreshold executions, and Connector/J needs useServerPrepStmts and cachePrepStmts with sensible cache sizes. We saw that reusing a generic plan can hurt skewed data, which PostgreSQL's plan_cache_mode can control, and that caches live per connection, so stable pools keep them warm while churn and transaction-mode poolers reduce or break the benefit.

What to say in the interviewAbout 90 seconds aloud

Open with

Beyond injection protection, the main benefit is that the database does not have to parse and plan the same statement every time. When a statement is prepared on the server, the parse and analysis happen once per connection, and later executions only send values, which saves database CPU and latency on hot queries.

Then, if they want more

How much of that we get depends on driver settings. The PostgreSQL driver uses the extended protocol and an unnamed statement at first, and after a statement has run prepareThreshold times on a connection, five by default, it switches to a named server-side statement, with a per-connection cache keyed by SQL text.

MySQL Connector/J by default only emulates prepared statements on the client, so I would set useServerPrepStmts=true and cachePrepStmts=true, and raise prepStmtCacheSize and prepStmtCacheSqlLimit, whose defaults are small. Two cautions.

Reusing a generic plan can be bad for skewed data: PostgreSQL may switch to a generic plan after five custom ones, and a rare value that needed an index can suddenly get a scan, so if a query slows down after a few executions I would check that and consider plan_cache_mode.

And all this caching is per connection, so it only pays off with a stable pool of long-lived connections. Pool churn means cold caches, and PgBouncer in transaction mode can break named statements unless it is a recent version that tracks them, or prepareThreshold is set to zero.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
java.sql, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Besides preventing SQL injection, what performance benefits can PreparedStatement bring...": https://scrivio-interview-library.netlify.app/databases/jdbc/0d295324c2/