一:考慮重建索引的場合
1:表上頻繁發生update,delete操作
2:表上發生了alter table ..move操作(move操作導致了rowid變化)
二:判斷重建索引的標準
索引重建是否有必要,一般看索引是否傾斜的嚴重,是否浪費了空間;
那應該如何才可以判斷索引是否傾斜的嚴重,是否浪費了空間,如下:
1, 對索引進行結構分析
Analyze index indexname validate structure;
2, 在執行步驟1的session中查詢index_stats表,不要到別的session去查詢
select height,DEL_LF_ROWS/LF_ROWS from index_stats;
3, 在步驟2查詢出來的height>=4或者DEL_LF_ROWS/LF_ROWS>0.2的場合,該索引考慮重建;
Example:
SQL> select count(*) from test_index;
COUNT(*)
----------
2072327
SQL> analyze index pk_t_test validate structure;
Index analyzed
SQL> select height,DEL_LF_ROWS/LF_ROWS from index_stats;
HEIGHT DEL_LF_ROWS/LF_ROWS
---------- -------------------
3 0
SQL> delete from test_index where rownum<250000;
249999 rows deleted
SQL> select height,DEL_LF_ROWS/LF_ROWS from index_stats;
HEIGHT DEL_LF_ROWS/LF_ROWS
---------- -------------------
3 0
SQL> analyze index pk_t_test validate structure;
Index analyzed
SQL> select height,DEL_LF_ROWS/LF_ROWS from index_stats;
HEIGHT DEL_LF_ROWS/LF_ROWS
---------- -------------------
3 0.0777430939338362
三:重建索引的方式
1:drop 原來的索引,然后再創建索引;
2:alter index indexname rebuild (online);
方式一:耗時間,無法在24*7環境中實現
方式二:比較快,可以在24*7環境中實現
建議使用方式二
四:alter index rebuid內部過程和注意點
1:alter index rebuild 和alter index rebuild online的區別
(1) 掃描方式不同
Rebuild以index fast full scan(or table full scan)方式讀取原索引中的數據來構建一個新的索引,有排序的操作; rebuild online 執行表掃描獲取數據,有排序的操作;
Rebuild 方式 (index fast full scan or table full scan 取決于統計信息的cost)
Eg1:
SQL> explain plan for alter index idx_policy_id2 rebuild;
Explained
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
---------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost |
---------------------------------------------------------------------
| 0 | ALTER INDEX STATEMENT | | 999K| 4882K| 3219 |
| 1 | INDEX BUILD NON UNIQUE| IDX_POLICY_ID2 | | | |
| 2 | SORT CREATE INDEX | | 999K| 4882K| |
| 3 | INDEX FAST FULL SCAN | IDX_POLICY_ID2 | 999K| 4882K| |
---------------------------------------------------------------------
Eg2:
SQL> explain plan for alter index idx_policy_id rebuild;
Explained
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
---------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost |
---------------------------------------------------------------------
| 0 | ALTER INDEX STATEMENT | | 2072K| 9M| 461 |
| 1 | INDEX BUILD NON UNIQUE| IDX_POLICY_ID | | | |
| 2 | SORT CREATE INDEX | | 2072K| 9M| |
| 3 | TABLE ACCESS FULL | TEST_INDEX | 2072K| 9M| 461 |
Eg3: (注意和Eg1比較)
Rebuil online 方式:
SQL> explain plan for alter index idx_policy_id2 rebuild online;
Explained
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
---------------------------------------------------------------------
| Id | Operation | Name