Tech Interview RoomStudy guides

Oracle

What are bind variables, hard vs soft parsing, and why do they matter for Java applications?

Intermediate · 2 min read · Lesson 3 of 5 in Oracle

When Oracle receives a SQL statement it must parse it:

  • Hard parse: syntax and semantic checks, optimisation and execution plan generation, then caching the cursor in the shared pool. Expensive in CPU and latches.
  • Soft parse: the same SQL text is already in the shared pool, so the cached plan is reused.

Bind variables

SQL that concatenates values (WHERE id = 42, WHERE id = 43, ...) produces a different text each time, so every execution is a hard parse, flooding the shared pool and hurting scalability. Using bind variables (WHERE id = :id, a PreparedStatement with ? in JDBC) keeps the SQL text identical, so the plan is reused. It is also the primary defence against SQL injection.

JPA/Hibernate, Spring's JdbcTemplate with parameters, and MyBatis #{} all use bind variables. MyBatis ${} and string concatenation do not.

Bind peeking and adaptive cursor sharing

On the first execution Oracle "peeks" at the bind values to choose a plan. With skewed data (99% of orders are CLOSED), a plan good for one value can be bad for another. Adaptive cursor sharing creates extra child cursors for different value ranges; histograms on skewed columns help the optimiser.

Client-side tips

Enable JDBC statement caching (oracle.jdbc.implicitStatementCacheSize), use batching for bulk inserts (addBatch), and set the fetch size for large result sets (the Oracle default is only 10 rows).

Example

java
// Bad: new SQL text per call → hard parse each time, and SQL injection
String sql = "SELECT name FROM customers WHERE email = '" + email + "'";

// Good: one shared cursor, values bound safely
try (PreparedStatement ps = conn.prepareStatement("SELECT name FROM customers WHERE email = ?")) {
    ps.setString(1, email);
    ps.setFetchSize(500);                    // fewer round trips for big result sets
    try (ResultSet rs = ps.executeQuery()) { /* ... */ }
}
sql
-- Find statements that are not using binds (many versions of almost the same SQL)
SELECT force_matching_signature, COUNT(*) AS versions, MIN(sql_text)
FROM v$sql
GROUP BY force_matching_signature
HAVING COUNT(*) > 50
ORDER BY versions DESC;

Follow-up questions interviewers ask

Try answering each one before you open it.

What does CURSOR_SHARING=FORCE do, and why is it a last resort?

It makes Oracle replace literals with system-generated binds so legacy applications reuse cursors. It can change execution plans unexpectedly (literals that should guide the optimiser become binds) and hides the real fix, which is using bind variables in the code.