JDBCmedium3-5 years
How does a PreparedStatement's plan cache actually save work compared to concatenated SQL, and what's the trade-off — parameter sniffing — that comes with it?
A PreparedStatement sends the SQL text once, with placeholders, and the database parses it into an execution plan; every later execution with different bound values reuses that same plan instead of parsing and planning from scratch. Concatenated SQL ("price < " + value) produces a different string on every call, so nothing can be cached or reused — a thousand different literal values means a thousand parses. The trade-off: a cached plan is chosen for whichever value ran first (or an average case) and then reused for everyone, so a plan that's fast for a common value can be badly wrong for a rare, skewed one — the phrase for this is parameter sniffing.
PreviousA LEFT JOIN in a query is supposed to keep customers with no orders, but the report is missing them. Separately, a total looks doubled. What are the two classic causes?Next A service prepares the identical SQL text on every request — a fresh PreparedStatement object each time — executes it once, and closes it. Does this ever get pgjdbc's server-side plan-reuse benefit, and what would need to change?