背景:如果表中有一列的数据分布很不均匀,大部分是1,少部分是0,而且我们经常查询的刚好是0,在这种情况下,走全表扫描的话,有些浪费资源,如 果对该列建立索引的话,那些值为1的索引数据又有些浪费,因为我们很少去查询值为1的数据,所以我们只对值为0的数据建立索引。
- create table t6(status char(1));
- begin
- for i in 1..100000 loop
- insert into t6 values('1');
- end loop;
- for i in 1..10 loop
- insert into t6 values('0');
- end loop;
- end;
对status列建立索引
- create index idx_t6_status on t6(status);
查询索引占用的块
- select index_name, i.leaf_blocks
- from user_indexes i
- where index_name = upper('idx_t6_status')
- INDEX_NAME LEAF_BLOCKS
- X_T6_STATUS 182
看到索引叶子块有182个,占用的比较多
下面我们只对status='0'建立索引来减少索引叶子块
- drop index idx_t6_status;
- create index idx_t6_status on t6(decode(status,'0','0'));
- 1 IDX_T6_STATUS 1
可以看到索引叶子块只有1个,数量减少了很多
通过索引查询status值为'0'的数据
- select * from t6 where decode(status, '0', '0') = '0'
执行计划如下
- SELECT STATEMENT, GOAL = ALL_ROWS 2 29 87
- TABLE ACCESS BY INDEX ROWID CARMOT_DEVELOP T6 2 29 87
- INDEX RANGE SCAN CARMOT_DEVELOP IDX_T6_STATUS 1 389