天天看點

ORACLE表與索引的分析

1.分析表與索引(analyze 不會重建索引)

analyze tabletablename compute statistics 

等同于 analyze table tablename compute statistics for table for all indexes forall columns

for table 的統計資訊存在于視圖:user_tables 、all_tables、dba_tables

for all indexes 的統計資訊存在于視圖: user_indexes 、all_indexes、dba_indexes

for all columns 的統計資訊存在于視圖:user_tab_columns、all_tab_columns、dba_tab_columns

注:分析表與索引見 AnalyzeAllTable存儲過程

2、一般來講可以采用以下三種方式來手工分析索引。

analyze index idx_t validate structure:

analyze index idx_t compute statistics:

analyze index idx_t estimate statistics sample 10 percent

1)analyze index idx_t validate structure:

這段分析語句是用來分析索引的block中是否有壞塊兒,那麼根據分析我們可以得到索引的結構資料,這些資料會保留到

index_stats中,來判斷這個索引是否需要rebuild. 需要注意的是這樣的分析是不會收集索引的統計資訊的。

2)validate structure有二種模式: online, offline, 一般來講預設的方式是offline。

當以offline的模式analyze索引時,會對table加一個表級共享鎖,對目前table的一些實時DMl操作會産生一定的影響。

而以online模式分析時候,則不會加任何lock,但在index_stats中是看不到任何資訊的。

3)analyze index idx_t compute statistics:

用來統計索引的統計資訊(全分析),主要為CBO服務。

4)analyze index idx_t estimate statisticssample 10 percent

主要是用來指定比例進行抽樣分析,也是為CBO服務. 例中是抽樣10%

3.重建索引

alter index index_name rebuild tablespace tablespace_name 

alter index index_name rebuild tablespace tablespace_name 加入表空間名,會将指定的索引移動到指定的表空間當中。

注:

analyze 操作隻是統計資訊,并将統計資訊存放起來供日後分析SQL使用,不進行重建之類的具體實施性操作,是以要重建索引的話

還是要用 alter index index_name rebuild

4、其他的統計方法

1)DBMS_STATS:這個當然是最強大的分析包了

--建立統計資訊曆史保留表

exec dbms_stats.create_stat_table(ownname => 'scott',stattab =>'stat_table');

--導出整個scheme的統計資訊

exec dbms_stats.export_schema_stats(ownname => 'scott',stattab =>'stat_table');

--分析scheme

Exec dbms_stats.gather_schema_stats(ownname => 'test',options => 'GATHERAUTO',

                                      estimate_percent => dbms_stats.auto_sample_size,

                                      method_opt => 'for all indexed columns',

                                      degree => 6 );

--分析表

exec dbms_stats.gather_table_stats(ownname => 'TEST',tabname =>'sm_user',estimate_percent => 10,method_opt=> 'for all indexed columns');

--分析索引

exec dbms_stats.gather_index_stats(ownname => 'TEST',indname =>'pk_user_index',estimate_percent => '10',degree => '4') ;

--如果發現執行計劃走錯,删除表的統計資訊

exec dbms_stats.delete_table_stats(ownname => 'TEST',tabname =>'SM_USER') ;

--導入表的曆史統計資訊

exec dbms_stats.import_table_stats(ownname => 'TEST',tabname =>'SM_USER',stattab => 'stat_table') ;

--如果進行分析後,大部分表的執行計劃都走錯,需要導回整個scheme的統計資訊

exec dbms_stats.import_schema_stats(ownname => 'TEST',stattab =>'SM_USER');

--導入索引的統計資訊

exec dbms_stats.import_index_stats(ownname => 'TEST',indname =>'PK_USER_INDEX',stattab => 'stat_table')

analyze和dbms_stats不同的地方:

analyze是同時更新表和索引的統計資訊,而dbms_stats會先更新表的統計資訊,然後再更新索引的統計資訊,

這裡就有一個問題,就是當表的統計資訊更新後,而索引的統計資訊沒有被更新,這時候cbo就有可能選擇錯誤的plan

2)DBMS_UTILITY.ANALYZE_SCHEMA:可直接分析SCHEMA中所有對象

   如:EXEC DBMS_UTILITY.ANALYZE_SCHEMA('LTTFM','COMPUTE');

3)DBMS_DDL.ANALYZE_OBJECT:收集對象的的統計資訊