From Cost Models to Neural Optimizers — A Practical Engineering Guide
Introduction
- What This Book Covers
- Who This Book Is For
- How to Use This Book
- Why PostgreSQL?
- Acknowledgments and Limitations
Chapter 1: The Problem of Query Optimization
- The Cost of Bad Query Plans
- Why Query Optimization Is NP-Hard
- The Gap Between Theoretical Optimality and Practical Constraints
- A Motivating Example: Cardinality Estimation Failure in Multi-Join Queries
- Overview of the Optimizer Pipeline and Where AI Can Intervene
- Scope and Roadmap of This Book
- References
Chapter 2: Anatomy of a Traditional Query Optimizer
- SQL Parsing and the Parse Tree
- From Parse Tree to Logical Query Representation
- The Query Optimization Pipeline in PostgreSQL
- EXPLAIN and EXPLAIN ANALYZE — Reading Plan Output
- Cost Model Components: CPU, I/O, Memory
- Planner Configuration Parameters and Their Effects
- Comparing PostgreSQL with Other Systems
- References
Chapter 3: Relational Algebra and Query Plans
- Basic Relational Operators
- Logical vs Physical Plans
- Algebraic Equivalences and Transformation Rules
- Left-Deep vs Bushy Join Trees
- PostgreSQL’s Join Tree Representation
- Building Alternative Plans Through Transformations
- Code Example: Parsing EXPLAIN JSON and Extracting Plan Structure
- References
Chapter 4: Statistics and Cardinality Estimation
- Table Statistics: Column Histograms, Most-Common-Values
- Correlation Handling and Dependency Statistics
- Join Selectivity Estimation
- PostgreSQL Statistics Collection: ANALYZE, Histogram Buckets
- Failure Modes: Skew, Outliers, Correlated Columns
- Impact of Estimation Errors on Plan Choice
- References
Chapter 5: Join Ordering and Search Strategies
- The NP-Hard Join Ordering Problem
- Dynamic Programming for Left-Deep Trees
- Greedy Search and Branch-and-Bound
- PostgreSQL’s GEQO Genetic Algorithm
- Query Decomposition and Join Graph Analysis
- Trade-offs: Optimality vs Planning Time
- References
Chapter 6: Indexing and Physical Design
- B-Tree Indexes: Structure, Cost, and Usage
- Hash Indexes and Bitmap Indexes
- Partial Indexes and Covering Indexes
- PostgreSQL: GiST, GIN, BRIN, SP-GiST
- Index Selection as Part of Query Optimization
- Multi-Dimensional Indexes and Composite Keys
- References
Chapter 7: Cost Models and Plan Selection
- The Total Cost Formula: CPU, I/O, Memory
- Cost Parameters in PostgreSQL
- Selectivity-Based Cost Computation
- Pipeline vs Materialization Costs
- Memory Grant Estimation
- Plan Selection: Choosing the Minimum-Cost Plan
- References
Chapter 8: Query Execution Engines
- Volcano Iterator Model
- Vectorized Execution
- Hash-Based Execution
- Nested Loop, Sort-Merge, Index Scan Strategies
- PostgreSQL’s Executor Internals
- The Plan Execution Feedback Loop
- References
Chapter 9: Caching, Reuse, and Parameterized Plans
- Prepared Statements and Plan Caching
- PostgreSQL: Prepared Statements and Plan Inference
- Parameter Sniffing and Plan Stability Issues
- Adaptive Plans and Parameter-Sensitive Plans
- Plan Reuse Trade-offs: Overhead vs Consistency
- Query Fingerprinting and Workload Analysis
- References
Chapter 10: Machine Learning Foundations for Database Optimization
- Supervised Learning: Regression and Classification for Cost Estimation
- Feature Engineering for Database Queries
- Model Families: Linear Models, Random Forests, Gradient Boosting
- Deep Learning Fundamentals Relevant to Query Optimization
- Graph Representations for Query Plans
- Evaluation Metrics: Prediction Accuracy vs Optimization Quality
- References
Chapter 11: Learned Cardinality Estimation
- Failure Modes of Traditional Histogram-Based Estimation
- Designing Features for Query Representation
- Random Forest Cardinality Estimators
- Deep Learning Approaches: RNNs, Transformers for Query Encoding
- Learned Histograms and Sampling-Based Methods
- Building a Learned Cardinality Estimator in Python
- Integration with PostgreSQL Optimizer
- References
Chapter 12: Learned Cost Models
- The Structure of Cost Models and Their Assumptions
- Learning Cost from Execution Traces
- Feature Engineering for Plan Cost Prediction
- Regression Models for Operator Cost Prediction
- Handling Distributional Shifts Across Hardware
- End-to-End Cost Model Training Pipeline
- Accuracy Requirements: What Margin of Error Matters
- References
Chapter 13: Learned Indexes
- The Learned Index Paper and Core Ideas
- Piecewise Linear Regression Models for Index Functions
- Adaptive Radix Trees and Learned Variants
- Learned Index Performance: Query Latency, Memory, Insertions
- Practical Implementations: Lucene, SQLite Extensions
- When Learned Indexes Help and When They Do Not
- References
Chapter 14: Neural Query Optimizers and Plan Selection
- Representing Queries and Plans as Graphs
- Graph Neural Networks for Plan Scoring
- Reinforcement Learning for Plan Search
- End-to-End Optimizers That Bypass Traditional Search
- Hybrid Approaches: ML-Guided Search Within Traditional Optimizers
- Training Data Generation and Reward Design
- References
Chapter 15: Workload-Aware Optimization
- Workload Classification and Clustering
- Temporal Patterns and Query Mixing
- Learning Workload-Specific Cost Parameters
- Adaptive Tuning Based on Workload Shifts
- PostgreSQL: Autovacuum and Workload Statistics
- Multi-Tenant and OLTP vs OLAP Workload Challenges
- References
Chapter 16: Automatic Index and Materialized View Selection
- The Index Recommendation Problem
- Greedy and Genetic Algorithm Approaches
- ML-Based Index Selection
- Materialized View Recommendation
- PostgreSQL: pg_hint_plan and Index Usage Feedback
- Cost-Benefit Trade-offs: Space vs Query Speed
- References
Chapter 17: Adaptive Query Optimization
- Progressive Feedback During Execution
- PostgreSQL: Adaptive Hash Joins
- Re-optimization and Query Reshaping
- Online Learning for Cardinality Estimation
- Plan Guidance and Forced Plans
- Safety: Preventing Adaptive Failures from Cascading
- References
Chapter 18: LLM-Based Query Reasoning and Optimization
- What LLMs Can and Cannot Do for Database Optimization
- Representing SQL and Query Plans for LLMs
- Prompting Strategies for Query Optimization Assistance
- Fine-Tuning LLMs on Plan Data
- Retrieval-Augmented Generation for Plan Recommendations
- Tool-Using Agents and Optimizer as LLM Tool
- Hallucination, Correctness, and Evaluation Risks
- Practical Architectures Combining LLMs with Traditional Optimizers
- References
Chapter 19: Building an AI-Assisted Optimizer: End-to-End System
- System Architecture: Data Collection, Model Serving, Optimizer Integration
- Designing the Training Data Pipeline from PostgreSQL
- Model Selection for Each Optimization Stage
- A/B Testing New Plans Against Baseline
- Gradual Rollout and Safety Mechanisms
- Complete Code Implementation Walkthrough
- References
Chapter 20: Evaluation, Benchmarking, and Correctness
- Benchmarks: TPC-H, TPC-DS, JOB, Custom Workloads
- Metrics: Execution Time, Latency Percentiles, Throughput
- Planning Overhead and Inference Latency
- Model Accuracy vs Optimization Quality: The Critical Distinction
- Regression Detection and Robustness Testing
- Generalization Across Schemas and Workloads
- References
Chapter 21: Production Deployment and Operations
- Model Serving Architecture: Latency, Throughput, Reliability
- Continuous Training and Drift Detection
- Observability: Logging, Metrics, Tracing
- Rollback Strategies and Plan Safety
- Handling Cold Starts and Data Scarcity
- Privacy, Security, and Access Control
- Team Skills and Organizational Considerations
- References
Chapter 22: Frontiers and Open Problems
- Open Research Problems in AI-Driven Optimization
- Scaling to Large Schemas and Complex Queries
- Cross-Database and Cloud-Native Optimization
- Federated and Distributed Query Optimization with ML
- The Path from Research to Production: Lessons Learned
- Future Directions and a Realistic Assessment
- References