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.