对部分行建立索引

背景:如果表中有一列的数据分布很不均匀,大部分是1,少部分是0,而且我们经常查询的刚好是0,在这种情况下,走全表扫描的话,有些浪费资源,如 果对该列建立索引的话,那些值为1的索引数据又有些浪费,因为我们很少去查询值为1的数据,所以我们只对值为0的数据建立索引。

Sql代码   收藏代码
  1. create table t6(status char(1));  
  2.   
  3. begin      
  4.   for i in 1..100000 loop  
  5.     insert into t6 values('1');  
  6.   end loop;  
  7.   for i in 1..10 loop  
  8.     insert into t6 values('0');  
  9.   end loop;  
  10. end;  

 对status列建立索引

Sql代码   收藏代码
  1. create index idx_t6_status on t6(status);  

 查询索引占用的块

Sql代码   收藏代码
  1. select index_name, i.leaf_blocks  
  2.   from user_indexes i  
  3.  where index_name = upper('idx_t6_status')  
Sql代码   收藏代码
  1. INDEX_NAME  LEAF_BLOCKS  
  2. X_T6_STATUS 182  
看到索引叶子块有182个,占用的比较多
 
下面我们只对status='0'建立索引来减少索引叶子块
Sql代码   收藏代码
  1. drop index idx_t6_status;  
  2.   
  3. create index idx_t6_status on t6(decode(status,'0','0'));  
  INDEX_NAME LEAF_BLOCKS
Sql代码   收藏代码
  1. 1   IDX_T6_STATUS   1  

 可以看到索引叶子块只有1个,数量减少了很多

 
通过索引查询status值为'0'的数据
Sql代码   收藏代码
  1. select * from t6 where decode(status, '0''0') = '0'  
 执行计划如下
Sql代码   收藏代码
  1. SELECT STATEMENT, GOAL = ALL_ROWS           2   29  87  
  2.  TABLE ACCESS BY INDEX ROWID    CARMOT_DEVELOP  T6  2   29  87  
  3.   INDEX RANGE SCAN  CARMOT_DEVELOP  IDX_T6_STATUS   1   389   
  转自:http://yufeng0471.iteye.com/blog/1059903

猜你喜欢

转载自fred-han.iteye.com/blog/1830129