Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is the benefit of using PreparedStatement for repeated queries, and how can a cached plan become a problem?

A PreparedStatement lets the database parse and plan a query once and then execute it many times with different values, which saves CPU, and because values are sent separately from the SQL text, it prevents SQL injection. The catch is that a plan cached for one value can be bad for another when data is skewed, such as a rare 'PENDING' status versus 'DONE' in 90 percent of rows. SQL Server calls this parameter sniffing; PostgreSQL may switch to a generic plan after five custom plans, and we fix it with plan_cache_mode, separate queries for skewed values or recompile hints.

Why this question is asked

Almost every Java application talks to its database through PreparedStatement, often without knowing it, because JPA, Spring's JdbcTemplate and JdbcClient all use it underneath. Interviewers ask about it because the benefits are well known, while the downside, a cached plan that suits one value and hurts another, explains some of the strangest performance bugs. In this answer, we will recap what a prepared statement is, see its two benefits, understand how a cached plan can go wrong with skewed data, and look at how SQL Server and PostgreSQL handle it and how we fix it.

1A Quick Recap of How a Query Runs

When a database receives SQL, it does several things before returning rows. It parses the text into a tree, checks that tables and columns exist, plans the query by choosing between possible ways to run it, such as an index scan or a full table scan, and only then executes the plan. For a short query, parsing and planning can cost as much CPU as executing it.

A prepared statement separates the query shape from its values. We write the SQL once with placeholders, the question marks, and then execute it many times, supplying the values each time.

Java
try (PreparedStatement ps = conn.prepareStatement(
"SELECT id, total FROM orders WHERE status = ? AND customer_id = ?")) {
ps.setString(1, "PENDING");
ps.setLong(2, 42L);
try (ResultSet rs = ps.executeQuery()) { /* ... */ } // same SQL text, new values each time
}

2Benefit 1: Parse and Plan Once

Because the SQL text never changes, the database can keep the parsed and planned statement and reuse it for every execution. When an order service runs the same lookup 5,000 times a second, skipping parse and plan on each call saves real CPU on the database server. The JDBC driver can also cache prepared statements per connection, so even code that calls prepareStatement each time can benefit.

In PostgreSQL's JDBC driver, this reuse starts after a statement has run a few times in a connection (the prepareThreshold setting, 5 by default), at which point the driver creates a named server-side prepared statement.

3Benefit 2: No SQL Injection

The second benefit is safety. Compare building SQL by concatenation with binding a value.

Java
String name = "x' OR '1'='1"; // typed by an attacker
stmt.executeQuery("SELECT * FROM users WHERE name = '" + name + "'");
// SQL becomes: ... WHERE name = 'x' OR '1'='1' -> returns every user
ps = conn.prepareStatement("SELECT * FROM users WHERE name = ?");
ps.setString(1, name);
ps.executeQuery(); // looks for a user literally named x' OR '1'='1 -> 0 rows

Notice the difference. With concatenation, the value becomes part of the SQL text and can change the query's meaning. With a parameter, the value travels separately and is always treated as data, never as SQL, so it cannot change the query.

4When a Cached Plan Becomes a Problem

Reusing a plan assumes that one plan is good for all values. That is true when values are spread evenly, but not when data is skewed. Imagine an orders table with 10 million rows where status = 'DONE' covers 90 percent of rows and status = 'PENDING' covers 0.1 percent.

One query, two very different best plans
ValueMatching rowsBest planWith the wrong cached plan
'PENDING'about 10,000 (0.1%)index scan, a few msfull scan, seconds
'DONE'about 9,000,000 (90%)sequential scanindex scan, many random reads
Skewed data means no single plan suits every value.

For PENDING, about 10,000 rows, an index scan is ideal. For DONE, 9 million rows, reading the whole table sequentially is cheaper than jumping through the index row by row. If the database caches the index plan and then runs it for DONE, or caches the sequential scan and runs it for PENDING, one of the two becomes far slower than it needs to be. The query text is identical; only the value differs.

5How SQL Server and PostgreSQL Handle It

SQL Server compiles a plan for the first values it sees and caches it for later executions. This is called parameter sniffing: the first parameters shape the plan everyone gets. If the first call after a restart happens to use a rare value, every later call uses the plan built for that rare value. SQL Server offers OPTION (RECOMPILE) to plan the query on every execution, and OPTIMIZE FOR hints to plan for a typical value.

PostgreSQL takes a more cautious approach. For the first five executions of a prepared statement, it builds a custom plan using the actual values. After that, it builds a generic plan, one that does not depend on the values, and compares its estimated cost with the average of the custom plans. If the generic plan does not look much worse, it keeps using it and saves the planning time. The risk is that the generic plan, built without knowing the value, is fine on average and bad for the skewed values.

6How We Fix It

In PostgreSQL, the setting plan_cache_mode, available since version 12, controls this choice. Setting it to force_custom_plan makes the database plan every execution with its real values. We apply it narrowly, to the role or session that runs the skewed query, because planning every time costs CPU.

SQL
ALTER ROLE reporting_app SET plan_cache_mode = force_custom_plan; -- only this application's sessions
-- or for one transaction:
SET LOCAL plan_cache_mode = force_custom_plan;

Another fix is to write separate queries for the skewed values, for example one method for pending orders and another for done orders, so each has its own cached plan. In SQL Server, OPTION (RECOMPILE) on the affected query does the same job as force_custom_plan. In every case, good statistics come first: if the database knows how skewed the column is, its custom and generic estimates are both more trustworthy.

7Follow-up questions

Do JPA and Spring use prepared statements?

Yes. Hibernate, JdbcTemplate and JdbcClient all send SQL through PreparedStatement with bound parameters, so they get both benefits by default. String-built native queries are the exception and should always use parameters too.

Is a prepared statement always faster?

Not always. For a query that runs once, preparing adds a round of work with no reuse. The gain comes from repeated execution, and the risk comes from skewed data, so most databases and drivers only start reusing plans after a statement has been used a few times.

Can you use a parameter for a table or column name?

No. Parameters can only stand for values. Table names, column names and sort directions must be part of the SQL text, so when they come from user input, we check them against a list of allowed values before building the query.

8Conclusion

In this answer, we saw that a PreparedStatement separates the SQL shape from its values, which lets the database parse and plan once and execute many times, and which prevents SQL injection because values are never treated as SQL. We also saw that a cached plan can be wrong for skewed data, the parameter sniffing problem in SQL Server and the generic plan problem in PostgreSQL, and that we fix it with plan_cache_mode = force_custom_plan, separate queries for skewed values, recompile hints and good statistics.

What to say in the interviewAbout 90 seconds aloud

Open with

A PreparedStatement has two benefits. First, the SQL is written once with placeholders, so the database can parse and plan it once and reuse that work for every execution, which saves CPU on hot queries.

Then, if they want more

Second, the values are sent separately and treated strictly as data, so a value like x' OR '1'='1 cannot change the query, which prevents SQL injection. The downside comes from reusing the plan.

If the data is skewed, say status PENDING is a tiny fraction of rows and DONE is ninety percent, the best plan differs by value: an index scan for PENDING and a sequential scan for DONE. A cached plan built for one is bad for the other.

In SQL Server that is called parameter sniffing, because the first values seen shape the cached plan. PostgreSQL uses custom plans with the real values for the first five executions and then may switch to a generic plan if its estimated cost is not much worse, and that generic plan can be wrong for the skewed values.

To fix it in PostgreSQL I would set plan_cache_mode to force_custom_plan for the specific role or transaction, or split skewed cases into separate queries; in SQL Server I would use OPTION RECOMPILE on that query. And I would make sure the statistics reflect the skew.

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.
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 "What is the benefit of using PreparedStatement for repeated queries, and how can a...": https://scrivio-interview-library.netlify.app/databases/query-optimization/6d69fa39a9/