Oracle 数据库的索引维护,说实话,是 DBA 绕不开的日常活儿。尤其你碰上那种用户量大、业务跑得快的系统,索引没整好,查询慢得像乌龟。这篇文章主要聊的是 Oracle 8i 里的B-tree 索引,怎么看、怎么查、怎么优化,写得还挺实用的。

系统表里的索引清查,建议你先看看有没有非系统用户的索引落在了表空间。这种操作风险蛮大,万一 SYSTEM 表空间出问题,整个库都跟着遭殃。你可以直接跑这个 SQL:

select count(*) from dba_indexes where tablespace_name = 'SYSTEM' and owner not in ('SYS', 'SYSTEM')

说说索引的存储结构。Oracle 底层用的是块(block)、范围(extent)、段(segment)这几层。想知道索引用了多少 extent,查一下dba_extents视图就行:

select segment_name, count(*) from dba_extents where segment_type='INDEX' and owner=UPPER('&owner') group by segment_name

再说到索引的选择性,这个概念其实挺重要。简单说,选择性高=定位精度高=查询快。你可以手动测算,像下面这样:

select count(distinct 列 1||'%'||列 2)/count(*) from 表名

也可以让 Oracle 自己来算:

analyze table 表名 compute statistics
select distinct_keys from user_indexes where table_name='表名' and index_name='索引名'
select num_rows from user_tables where table_name='表名'

索引平时也得按时体检:定期、重建、甚至删除没用的索引,才能让系统不掉链子。如果你做 DBA,或者你在管一堆高并发业务库,这篇文章还是蛮值得一读的。

哦对了,下面这些延伸阅读也挺不错的: