PostgreSQL Enterprise (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
What is Query Plan Invalidation and Parameter Sniffing in Prepared Statements?
senior LevelForms
In Simple Words:
When executing prepared statements (PREPARE my_query AS ...):
- For the first 5 executions, PostgreSQL generates a custom plan for the specific parameter value.
- On the 6th execution, it generates a Generic Plan independent of parameters.
- If data is heavily skewed (e.g.
status = 'ACTIVE'matches 99% of rows, butstatus = 'ERROR'matches 0.01%), the generic plan may pick a sequential scan, causing severe performance drops! - Fixed in PostgreSQL 14+ via smarter plan choice tracking.