####4.2.1 聚簇因子(clustering_factor)
统计帮助优化器生成使用索引的成功信息,并且是表中建立了索引的数据排序优良度的一个度量值;向优化器表明了具有同样索引值的数据行是不是存放在同一个或连续的一系列数据块中,或者数据行是否被分散存放在表的多个数据块中。
查看索引的聚簇因子
select T.TABLE_NAME || '.' || I.INDEX_NAME index_name, I.CLUSTERING_FACTOR, T.BLOCKS, T.NUM_ROWS
from user_indexes i, user_tables t
where I.TABLE_NAME = T.TABLE_NAME
and T.TABLE_NAME = 'EMPLOYEES'
and I.INDEX_NAME = 'EMP_DEPARTMENT_IX'
order by T.TABLE_NAME, I.INDEX_NAME;
INDEX_NAME CLUSTERING_FACTOR BLOCKS NUM_ROWS
------------------------------ ----------------- ---------- ----------
EMPLOYEES.EMP_DEPARTMENT_IX 9 5 109
计算索引的聚簇因子
select department_id, last_name, blk_no,
lag (blk_no, 1, blk_no) over (order by department_id) prev_blk_no,
case when blk_no != lag (blk_no, 1, blk_no) over (order by department_id) or rownum = 1
then '*** +1'
else null
end cluf_ct
from (
select department_id, last_name,
DBMS_ROWID.ROWID_BLOCK_NUMBER(rowid) blk_no
from HR.EMPLOYEES
where department_id is not null
order by department_id
);
DEPARTMENT_ID LAST_NAME BLK_NO PREV_BLK_NO CLUF_CT
------------- ------------------------- ---------- ----------- -------
10 Whalen 203 203 *** +1
20 Hartstein 203 203
20 Fay 203 203
30 Raphaely 207 203 *** +1
30 Colmenares 207 207
30 Khoo 207 207
........
40 Mavris 203 207 *** +1
50 Grant 203 203
........
50 Cabrio 207 203 *** +1
........
60 Raphealy 205 207 *** +1
60 Raphealy1 205 205
60 Austin 207 205 *** +1
60 Ernst 207 207
60 Hunold 207 207
70 Baer 203 207 *** +1
80 Hall 207 203 *** +1
80 Livingston 207 207
........
100 Greenberg 207 207
110 Higgins 203 207 *** +1
110 Gietz 203 203
107 rows selected.
注: 如果你开始考虑重建表来改进聚簇因子,你需要很小心。表一般都有多个索引。你不可能通过重建表的方法使其排序方式适合某个索引而不影响其他列上的索引。因此,重建可能帮组改进了一个索引却破坏了其他的索引。并且,重建表通常是非常耗费时间和资源的过程,因为你今天按照一定的顺序重建了表并不意味着随着时间的推移,数据行插入、更新或删除之后还能保持这样的顺序。