提升 PostgreSQL 查询性能
Amy McCarty
Instructor
| 系统 | 前端步骤 | 后端进程 | |
|---|---|---|---|
| 1 | 解析器 | 将查询发送到数据库 | 检查语法。根据系统规则将 SQL 转为更易处理的语法。 |
| 2 | 计划器与优化器 | 评估并优化查询任务 | 使用数据库统计创建查询计划。计算成本并选择最佳方案。 |
| 3 | 执行器 | 返回查询结果 | 按查询计划执行。 |
响应 SQL 结构变化
SELECT * FROM pg_class
WHERE relname = 'mytable'
-- sample of output columns
| relname | relhasindex |
SELECT * FROM pg_stats
WHERE tablename = 'mytable'
-- sample of output columns
null_frac | avg_width | n_distinct |
EXPLAIN
SELECT * FROM cheeses
Seq Scan on cheeses
(cost=0.00..10.50 rows=5725 width=296)
Seq Scan on cheeses (cost=0.00..10.50 rows=5725 width=296)
Seq Scan on cheeses (cost=0.00..10.50 rows=5725 width=296)
..10.50:总时间
总时间 = 启动 + 运行时间
Seq Scan on cheeses (cost=0.00..10.50 rows=5725 width=296)
EXPLAIN
SELECT * FROM cheeses WHERE species IN ('goat','sheep')
Seq Scan on cheeses (cost=0.00..378.90 rows=3 width=118)
-> Filter: (species = ANY ('{"goat","sheep"}'::text[]))
EXPLAIN
SELECT * FROM cheeses WHERE species IN ('goat','sheep') -- index on species column
Bitmap Index Scan using species_idx on cheeses (cost=0.29..12.66 rows=3 width=118)
Index Cond: (species = ANY ('{"goat","sheep"}'::text[]))
提升 PostgreSQL 查询性能