PostgreSQLでクエリ性能を改善する
Amy McCarty
Instructor
| システム | フロントエンドの手順 | バックエンドの処理 | |
|---|---|---|---|
| 1 | Parser | クエリをDBへ送信 | 構文を検査。システムの規則に基づきSQLを機械向け表現へ変換。 |
| 2 | Planner & Optimizer | クエリを評価・最適化 | DB統計に基づきクエリ計画を作成。コストを算出し最適な計画を選択。 |
| 3 | Executor | 結果を返す | 計画に従ってクエリを実行。 |
SQL構造の変更に追随
SELECT * FROM pg_class
WHERE relname = 'mytable'
-- 出力列の例
| relname | relhasindex |
SELECT * FROM pg_stats
WHERE tablename = 'mytable'
-- 出力列の例
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でクエリ性能を改善する