← Lessons

quiz vs the machine

Gold1410

Databases

Prepared Statements and Plan Caching

Parse and plan a query once, then run it many times with new values.

4 min read · core · beat Gold to climb

Separating Query from Values

A prepared statement sends the query text with placeholders for values, like a question with blanks. The database parses and plans it once, then you execute it repeatedly by supplying just the values.

Two Big Wins

  • Performance improves because parsing and planning happen once and the cached plan is reused.
  • Security improves because values travel separately from the query text, which stops SQL injection. User input can never change the query structure.

Plan Caching Caveats

A cached plan was chosen for the first values it saw. If later values have very different data distributions, a generic plan may be slower than a fresh one. Good engines detect this and sometimes replan.

Practical Notes

  • Most database drivers and connection pools handle preparation for you.
  • Plans are usually cached per connection, so a fresh connection reprepares.

Key idea

Prepared statements parse and plan a query once for reuse, boosting performance and blocking SQL injection by keeping user values separate from the query text.

Check yourself

Answer to earn rating on the learn ladder.

1. How do prepared statements prevent SQL injection?

2. What is a caveat of reusing a cached plan?