一:考慮重建索引的場合
1:表上頻繁發(fā)生update,delete操作
2:表上發(fā)生了alter table ..move操作(move操作導(dǎo)致了rowid變化)
二:判斷重建索引的標(biāo)準(zhǔn)
索引重建是否有必要,一般看索引是否傾斜的嚴(yán)重,是否浪費(fèi)了空間;
那應(yīng)該如何才可以判斷索引是否傾斜的嚴(yán)重,是否浪費(fèi)了空間,如下:
1, 對索引進(jìn)行結(jié)構(gòu)分析
Analyze index indexname validate structure;
2, 在執(zhí)行步驟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 原來的索引,然后再創(chuàng)建索引;
2:alter index indexname rebuild (online);
方式一:耗時(shí)間,無法在24*7環(huán)境中實(shí)現(xiàn)
方式二:比較快,可以在24*7環(huán)境中實(shí)現(xiàn)
建議使用方式二
四:alter index rebuid內(nèi)部過程和注意點(diǎn)
1:alter index rebuild 和alter index rebuild online的區(qū)別
(1) 掃描方式不同
Rebuild以index fast full scan(or table full scan)方式讀取原索引中的數(shù)據(jù)來構(gòu)建一個(gè)新的索引,有排序的操作; rebuild online 執(zhí)行表掃描獲取數(shù)據(jù),有排序的操作;
Rebuild 方式 (index fast full scan or table full scan 取決于統(tǒng)計(jì)信息的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