Full answer
Benefits:
- Parameters are sent separately from the SQL, so user input cannot change the statement's structure.
- Repeated statements skip parsing and, when a generic plan is cached, planning.
Pitfalls:
- Skewed data:
WHERE status = $1may deserve an index scan for rare statuses and a sequential scan for common ones. A generic plan picks one for all. PostgreSQL plans custom plans for the first five executions and then switches to a generic plan if it is not estimated to be worse;plan_cache_mode = force_custom_planoverrides that. - Schema changes invalidate cached plans; most engines replan automatically.
- Connection poolers in transaction mode historically broke named prepared statements, because the next execution may land on another server connection. Newer PgBouncer versions track them.
SQLite caches compiled statements in the driver (Python's sqlite3 keeps a statement cache) and plans with the actual parameter values only in limited cases. These behaviours are described here, not run.
Key points
- Prepare once, execute many
- Parameters prevent SQL injection
- Generic plans can misfit skewed values
- PostgreSQL chooses custom or generic plans adaptively
- Poolers may interfere with named statements
Common mistakes
- Building SQL by string concatenation
- Blaming the query when a generic plan is the cause
Follow-ups
- How would you detect a bad generic plan?
- Can identifiers such as table names be parameters?
Tips
- Mention injection and plan reuse together