What You Will Master
1. How PostgreSQL Executes Queries
Text
2. Reading Execution Plans: EXPLAIN (ANALYZE, BUFFERS)
Sql
- ANALYZE: Actually runs the query, reporting real wall-clock execution times alongside planner estimates.
- BUFFERS: Displays shared memory buffer hits, reads from disk, and writes.
Anatomy of an Execution Plan
Text
Understanding the Key Metrics:
- cost=142.15..142.27:
- 142.15 is the startup cost (cost to fetch the very first row).
- 142.27 is the total cost (cost to return all rows for this node). Cost is an arbitrary unit where 1.0 equals a single sequential disk page fetch (seq_page_cost).
- actual time=0.450..1.420: Real time in milliseconds for first row returned and completion of that node.
- shared hit vs read:
- shared hit: Pages found directly in PostgreSQL's RAM (shared_buffers). This is fast (microseconds).
- read: Pages fetched from the OS page cache or disk. Disk reads are the primary cause of query latency.
The Four Core Scan Types
3. PostgreSQL Index Types & Selection Guide
1. B-Tree (Default Workhorse)
- Under the Hood: Balanced search tree maintaining sorted order with self-balancing properties.
- Supported Operators: <, <=, =, >=, >, BETWEEN, IN, IS NULL, and ORDER BY.
- Best Used For: Primary keys, foreign keys, timestamps, numeric IDs, and equality checks.
Sql
2. GIN (Generalized Inverted Index)
- Under the Hood: Inverted index where each element maps to a list of rows containing that element.
- Supported Operators: Array operations (&&, @>, <@), JSONB containment (@>, ?, ?&), and Full-Text Search (tsvector @@ tsquery).
- Best Used For: Searching tags, JSONB documents, or text search catalogs.
Sql
3. GiST (Generalized Search Tree)
- Under the Hood: Balanced, tree-structured access method acting as a base template for arbitrary indexing schemes.
- Supported Operators: Geometric overlap (&&), containment (@>), distance/nearest-neighbor (<->), and range overlap (&&).
- Best Used For: PostGIS spatial coordinates, IP address ranges (inet), and booking interval ranges (tstzrange).
Sql
4. BRIN (Block Range Index)
- Under the Hood: Stores only the minimum and maximum values for physical blocks of pages (default 128 pages per range).
- Storage Footprint: 99% smaller than a B-Tree. A 50GB table might need a 5GB B-Tree index, but only a 5MB BRIN index!
- Best Used For: Massive append-only tables where data is naturally correlated with physical storage order (e.g. created_at timestamps in event logs or sensor metrics).
Sql
4. Advanced Indexing Strategies
Strategy 1: Partial Indexes (Slash Storage & Write Costs)
Sql
- Index size drops from 400MB to 2MB.
- Inserts and updates for "completed" orders suffer zero index write overhead.
- Cache fits entirely inside RAM (shared_buffers).
Strategy 2: Covering Indexes with INCLUDE (Index-Only Scans)
Sql
Strategy 3: Multi-Column Indexes & The Leftmost Prefix Rule
- (A)
- (A, B)
- (A, B, C)
Sql
5. Step-by-Step Optimization: A Real-World Case Study
The Problematic Query
Sql
Initial Execution Plan (Before Optimization)
Text
- Full Seq Scan: Read 4,198,590 rows only to discard them.
- I/O Footprint: Read 38,412 pages (~300MB) from disk.
- Latency: 482ms, causing thread starvation under concurrent traffic.
The Targeted Index Solution
Sql
[!NOTE] Always use CREATE INDEX CONCURRENTLY in production environments. Standard index creation locks the table against writes (SHARE lock), whereas concurrent builds allow ongoing INSERT, UPDATE, and DELETE transactions.
Optimized Execution Plan (After Optimization)
Text
The Result:
- Execution Time: Dropped from 482.35ms to 0.088ms (5,480x faster).
- Buffer I/O: Reduced from 38,412 pages read to 4 shared hits in RAM.
- Scan Type: Promoted from Seq Scan to zero-heap Index Only Scan.
6. Common Database Performance Traps to Avoid
1. Wrapping Indexed Columns in Functions
Sql
2. High-Offset Pagination (OFFSET 50000)
Sql
3. Missing Foreign Key Indexes
Sql
7. Monitoring Slow Queries in Production with pg_stat_statements
Sql
Common Questions
Why does PostgreSQL use a Seq Scan even when an index exists?
What is the performance overhead of adding too many indexes?
How often should I run VACUUM and ANALYZE?
What is the difference between B-Tree and BRIN?
Final Takeaway
- Profile First: Use EXPLAIN (ANALYZE, BUFFERS) to locate the exact bottleneck (disk reads vs CPU sort).
- Select the Right Index: Match the data shape to the index type (B-Tree for ranges/equality, GIN for JSONB/arrays, BRIN for time series).
- Use Partial and Covering Indexes: Reduce index size and achieve zero-heap Index Only Scans.
- Monitor Continually: Leverage pg_stat_statements to catch slow queries before your users do.