← Back to SQL, page 20

sql-0388 · Medium mid

How do prepared statements and plan caching affect performance and correctness?

A prepared statement is parsed and planned once and executed many times with parameters, which saves parsing work and keeps data separate from SQL text, preventing injection. Some engines reuse a generic plan that ignores parameter values, which can be poor for skewed data. PostgreSQL decides between custom and generic plans after several executions.

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 = $1 may 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_plan overrides 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