47 lines
1.5 KiB
Markdown
47 lines
1.5 KiB
Markdown
---
|
|
title: "Query Plan Analysis"
|
|
type: concept
|
|
tags: [database, postgresql, explain, performance, query-optimization]
|
|
last_updated: 2026-05-01
|
|
---
|
|
|
|
# Query Plan Analysis
|
|
|
|
## Definition
|
|
|
|
查询计划分析是通过 `EXPLAIN ANALYZE` 命令解读数据库优化器生成的查询执行计划,识别性能瓶颈(如 Seq Scan 全表扫描、估算偏差大)并针对性优化的方法。
|
|
|
|
## Key Scan Types
|
|
|
|
| 扫描类型 | 评估 | 说明 |
|
|
|---------|------|------|
|
|
| **Seq Scan** | ⚠️ 差 | 全表扫描,通常意味着缺索引 |
|
|
| **Index Scan** | ✅ 好 | 索引扫描,直接定位数据 |
|
|
| **Bitmap Heap Scan** | 🟡 可接受 | 先索引定位再堆查,适合中等结果集 |
|
|
| **Index Only Scan** | ✅ 最佳 | 完全在索引中完成,无需回表 |
|
|
|
|
## What to Look For
|
|
|
|
- **actual time vs estimated rows**:与估算差异大说明统计信息过时
|
|
- **cost=... loops=...**:高 cost 或多次 loops 需优化
|
|
- **Buffers: shared hit/read**:大量 read 说明缓存未命中
|
|
- **Seq Scan on large tables**:大表全表扫描通常是问题信号
|
|
|
|
## Example
|
|
|
|
```sql
|
|
EXPLAIN ANALYZE
|
|
SELECT * FROM posts WHERE user_id = 123;
|
|
|
|
-- Good: Index Scan
|
|
-- Bad: Seq Scan on posts (cost=0.00..1234.56 rows=500 width=...)
|
|
```
|
|
|
|
## Source
|
|
- [[engineering-database-optimizer]]
|
|
|
|
## Connections
|
|
- [[IndexingStrategies]] — 根据分析结果创建/调整索引
|
|
- [[N1QueryPrevention]] — EXPLAIN 识别 N+1 查询
|
|
- [[SafeMigrations]] — 迁移前后验证查询性能
|