改進 PostgreSQL 的查詢效能
Amy McCarty
Instructor
| 系統 | 前端步驟 | 後端處理 | |
|---|---|---|---|
| 1 | Parser | 將查詢送到資料庫 | 檢查語法。依系統規則將 SQL 轉成較易處理的語法。 |
| 2 | Planner & Optimizer | 評估並最佳化查詢工作 | 用資料庫統計建立查詢計畫。計算成本並選最佳計畫。 |
| 3 | Executor | 回傳查詢結果 | 依查詢計畫執行查詢。 |
隨 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 的查詢效能