重建索引(rebuild index)與sort
2024-07-21 02:34:39
供稿:網友
重建索引到底要不要排序?有人說要,因為創建索引時需要排序。有人說不要,因為重建索引的時候可以直接掃描舊的索引來重建成新的索引。讓我們來看一下rebuild index到底需不需要排序。
SQL> select name,statistic# from v$statname where name like '%sort%';
NAME STATISTIC#
---------------------------------------------------------------- ----------
sorts (memory) 242
sorts (disk) 243
sorts (rows) 244
看一下排序操作相關的 stat號
再看一下rebuild index 的執行路徑 SQL> eXPlain plan for alter index ind_test_id rebuild;
Explained.
SQL> @?/rdbms/admin/utlxpls
PLAN_TABLE_OUTPUT
-----------------------------------------------------------------------
Id Operation Name Rows Bytes Cost
-----------------------------------------------------------------------
0 ALTER INDEX STATEMENT 17837 71348 11
1 INDEX BUILD NON UNIQUE IND_TEST_ID
2 SORT CREATE INDEX 17837 71348
3 INDEX FAST FULL SCAN IND_TEST_ID 17837 71348 11
-----------------------------------------------------------------------
執行下rebuild 看看
SQL> select STATISTIC#,value from v$mystat where STATISTIC# in(242,243,244);
STATISTIC# VALUE
---------- ----------
242 154
243 0
244 242
SQL> alter index ind_test_id rebuild;
Index altered.
SQL> select STATISTIC#,value from v$mystat where STATISTIC# in(242,243,244);
STATISTIC# VALUE
---------- ----------
242 155
243 0
244 242
可以看出sort(memory)增加了一次
為什么要排序呢?因為rebuild index的時候走的index ffs,而ffs搜索的順序是根據 leaf block 的物理存儲順序相關而跟鍵值的邏輯順序無關(在"index full scan vs fast index full scan"這篇文章中有具體介紹), 所以ffs的結果必須再做一次排序。
此外在rebulid index online的時候走的是full table scan,這時候也是需要排序的,而且排序的次數會比較多, 在測試中發現每次做rebuild online產生4(10g中為13)次sort(memory),可能跟一些遞規排序有關系。10g里面重建索引排序又有了一些改變,在10032事件的跟蹤文件里面出現“Reopened sort”,目前暫時不知道是什么意思,希望有朋友能就這個問題進行探討。