Prepared statements

Values sent separately from the SQL: parameter binding, the plan cache, generated keys, and the return value people ignore.

9 min read🐘 Relational Databases in Depth

A PreparedStatement sends the SQL and the values separately: the statement goes first with placeholders, the database parses it into a plan, and the values arrive afterwards as values. That one property is worth two different things — a security guarantee and a performance one — and they are worth separating, because people learn the first and miss the second.

The security half has its own lesson, Injection, in the security course: why parameters work where escaping does not, and what placeholders cannot cover. This lesson is the JDBC mechanism.

The shape

java
try (PreparedStatement ps = c.prepareStatement(
        "select id, name from item where price < ? and name like ?")) {
    ps.setInt(1, 500);
    ps.setString(2, "b%");
    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) { ... }
    }
}

Three things that trip people on the first day:

  • Parameter indexes start at 1, not 0. Everything else in Java starts at 0; this does not, because it follows SQL.
  • A ? stands for one value. where id in (?) cannot take a list. You build in (?, ?, ?) for the size you have, or use setArray where the driver supports it.
  • The % belongs in the value, not the SQL. like ? with "b%" — not like '?%', which is a literal question mark.

Setting NULL

java
ps.setString(2, null);              // works for most drivers
ps.setNull(2, Types.VARCHAR);       // explicit, and portable

The typed form exists because some drivers cannot infer the SQL type of a null and will reject the statement. setNull is the habit worth having, and it is also self-documenting at the call site.

The plan cache, which is the half people miss

Parsing SQL and choosing a plan is real work — for a complex query it can cost more than running it. Because a prepared statement's text never changes, the database can keep the plan and reuse it for every set of values.

Concatenated SQL cannot be cached, because every execution is a different string:

sql
select * from item where price < 500     -- a new statement
select * from item where price < 750     -- and another
select * from item where price < 900     -- and another

A thousand values means a thousand parses and a thousand cache entries, evicting everything else. The same query as a parameterised statement is one entry, parsed once.

Reuse the statement, not just the string

The performance argument only pays if you prepare once and execute many times:

java
// prepared once, outside the loop
try (PreparedStatement ps = c.prepareStatement("insert into event values (?, ?)")) {
    for (Event e : events) {
        ps.setInt(1, e.id);
        ps.setString(2, e.payload);
        ps.executeUpdate();
    }
}

Preparing inside the loop asks the driver to prepare a thousand times. Many drivers and pools cache prepared statements per connection anyway — HikariCP's cachePrepStmts for MySQL, PostgreSQL's own server-side cache after a few executions — but writing the loop this way is free and does not depend on a setting being on.

And note what this loop still does badly: one network round trip per row. That is the batching lesson, next.

Getting the generated key back

An insert into a table with a generated id usually needs that id:

java
try (PreparedStatement ps = c.prepareStatement(
        "insert into orders (customer_id, total) values (?, ?)",
        Statement.RETURN_GENERATED_KEYS)) {
    ps.setLong(1, customerId);
    ps.setInt(2, total);
    ps.executeUpdate();
    try (ResultSet keys = ps.getGeneratedKeys()) {
        if (keys.next()) orderId = keys.getLong(1);
    }
}

The flag has to be passed at prepareStatement time — asking afterwards is too late, because the driver had to tell the database to return them. On PostgreSQL the more explicit alternative is insert ... returning id, executed as an ordinary query.

executeQuery, executeUpdate, execute

  • executeQuery returns a ResultSet. For a select.
  • executeUpdate returns the number of rows affected. For insert, update, delete — and that number is worth checking. An update that affects 0 rows usually means the where matched nothing, which is a silent no-op you would rather hear about.
  • execute returns a boolean and is for when you do not know which you have. Rare in application code.

Where this shows up above JDBC

JdbcTemplate and JdbcClient use prepared statements for every parameterised call — you get the mechanism without writing it. JPA does too: setParameter on a JPQL query becomes a bind variable, which is why the JPA course insists on named parameters rather than string building, and why a native @Query with concatenation gives up both halves of this lesson at once.

Under the hood: a PreparedStatement is not automatically a server-side prepared statement

The plan-cache section above described why preparing pays off — the database can reuse a compiled plan. What it did not say is where that plan gets prepared, and calling prepareStatement() in Java does not necessarily mean the database prepared anything yet.

There are two places "preparing" can happen, and JDBC's name blurs them together:

  • Client-side ("emulated") preparation. The driver holds the SQL text and your bound values in Java, and on execute*() sends one fully-substituted (but still safely parameterised, via the wire protocol's own Bind step — never string concatenation) statement to the database. The database parses and plans it fresh, as if you had sent an ordinary query. No server-side plan is cached.
  • Server-side preparation. The driver actually sends the database a PREPARE-equivalent message, the database compiles a named plan and holds it for the life of the session, and each execute*() after that sends only the parameter values, referencing the already-compiled plan by name.

Only the second one gets you the plan-reuse benefit described above — and drivers do not always choose it by default, because server-side preparation has its own cost (a round trip to prepare, and server-side memory held for the statement's lifetime) that only pays off if the statement really does run more than once. PostgreSQL's JDBC driver (pgjdbc), for instance, defaults to emulating preparation for the first few executions of a given PreparedStatement object and only switches it to a genuine server-side prepared statement once it has been executed a threshold number of times (prepareThreshold, five by default) — on the theory that a statement executed once is not worth the extra round trip to prepare server-side, but a statement executed in a loop is. This is a driver-level policy, not a JDBC-spec guarantee, and other drivers make different defaults; the number to remember is not "5" so much as "check whether your driver prepares server-side immediately, after N executions, or not by default at all" before assuming the plan cache in the earlier section is actually being used.

Try it yourself

Reason through emulated vs. server-side preparation

A service prepares the same PreparedStatement text once per incoming HTTP request (a fresh PreparedStatement object each time, even though the SQL string is character-for-character identical), executes it once, and closes it. The database driver defaults to server-side preparation only after the same statement object has been executed several times.

Will this service's queries ever get a server-side compiled plan reused across requests, assuming nothing else changes?

Not from this alone — the threshold is per statement object, not per SQL text

A driver that counts executions against a specific PreparedStatement object will never see that count go above one, because a new object is created (and discarded) on every request — the identical SQL text does not help, because the driver is not tracking "have I seen this text before" by default, it is tracking "has this particular Java object been executed enough times." The plan-cache benefit described earlier in this lesson requires either reusing the same PreparedStatement object across executions (the "prepare once, execute many" loop) or a driver/pool-level statement cache that recognises identical SQL text across different PreparedStatement objects on the same physical connection and reuses a server-side plan for it — which is a separate feature from JDBC's own API, configured at the driver or pool level, not something prepareStatement() gives you automatically.

Misconceptions

  • "Calling prepareStatement() means the database has now compiled and cached a plan." Only if the driver chooses server-side preparation, and many drivers do not do that by default on the first few executions — see above. Calling the method guarantees the JDBC-level contract (SQL and values sent separately); it does not guarantee server-side plan reuse.
  • "A ? placeholder is always exactly as fast as a literal value, so there's no reason to ever write a literal." For an equality filter this is usually true and preparing is strictly better. For a highly skewed column, a generic plan chosen once to fit "typical" values can be measurably worse for an unusual one than a fresh plan computed for that specific literal — which is the parameter-sniffing trade-off above. Parameters remain the right default; the point is that "prepared" is not a synonym for "cannot be slower than a literal."

Sources

  • PostgreSQL JDBC driver (pgjdbc) documentation — "Server Prepared Statements" and the prepareThreshold connection parameter.
  • PostgreSQL documentation — PREPARE and the extended query protocol (Parse/Bind/Execute).
  • Vlad Mihalcea, "How does PreparedStatement caching work" (JDBC and Hibernate statement-caching writing).
Progress is saved on this device and to your account when signed in.