DB2 同樣採用基於成本的優化器 (CBO),根據 CPU 成本、I/O 成本、系統目錄統計信息及 SQL 語句本身四大因素評估存取路徑。優化器流程:語法校驗 → 生成最優計劃 → 轉譯執行 → 返回/儲存結果。
系統目錄統計信息是優化器的核心依據,涵蓋表(記錄數、頁面、PCTFREE)、欄位(數量、長度、分布)、索引(存在性、組織、離散值、叢集性)及分區/表空間信息。
以下情況必須執行 RUNSTATS:
REORG 後(高水位等變化)。REDISTRIBUTE DATABASE PARTITION GROUP 後。語法範例:
db2 runstats on table db2inst1.staff with distribution and detailed indexes all
建議定時結合 REORG → RUNSTATS → REBIND。快速變化表可設為 VOLATILE:
alter table table_name volatile cardinality
REORGCHK 判斷是否需重整:
db2 reorgchk update statistics on table system
db2 reorgchk update statistics on table user
大量操作安排在閒時。關閉自動維護:
db2 update db cfg using AUTO_MAINT off AUTO_TBL_MAINT off AUTO_RUNSTATS off
LOAD 不記日誌、效率極高。裝載時指定 STATISTICS 選項:
load from mobile_number.del of del replace into mobile statistics yes with distribution and detailed indexes all
load from mobile_number.del of del replace into mobile statistics yes and indexes all
load from mobile_number.del of del replace into mobile statistics use profile
用於開發/生產環境同步執行計劃:
db2 runstats on table .
db2look -d -t -m -o statis.sql
db2 -svtf statis.sql
總結
基於成本的優化器決定 SQL 效率,正確及時收集統計信息是生成正確執行計劃的關鍵。實際環境各異,但核心工具與原則一致。
- 上一篇文章: 解決 DB2 數據庫文件系統已滿錯誤 (SQLCODE -968C) 的方法
- 下一篇文章: DB2 數據庫優化六大核心策略實戰解析
Copyright © 程式碼之家 All Rights Reserved