---
title: "对部分行建立索引"
author: "Fred_Han"
date: "2013-03-15T16:21:45Z"
tags: []
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2013-03-15T16:21:45Z"
id: 1830129
url: "https://fred-han.iteye.com/blog/1830129"
---

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

 

 

Sql代码  [![收藏代码](http://yufeng0471.iteye.com/images/icon_star.png)]()

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

 对status列建立索引

 

Sql代码  [![收藏代码](http://yufeng0471.iteye.com/images/icon_star.png)]()

1. create index idx\_t6\_status on t6(status);

 查询索引占用的块

 

Sql代码  [![收藏代码](http://yufeng0471.iteye.com/images/icon_star.png)]()

1. select index\_name, i.leaf\_blocks
2. from user\_indexes i
3. where index\_name = upper('idx\_t6\_status')

Sql代码  [![收藏代码](http://yufeng0471.iteye.com/images/icon_star.png)]()

1. INDEX\_NAME  LEAF\_BLOCKS
2. X\_T6\_STATUS 182

看到索引叶子块有182个，占用的比较多

 

下面我们只对status='0'建立索引来减少索引叶子块

Sql代码  [![收藏代码](http://yufeng0471.iteye.com/images/icon_star.png)]()

1. drop index idx\_t6\_status;
2. create index idx\_t6\_status on t6(decode(status,'0','0'));

  INDEX\_NAME LEAF\_BLOCKS

Sql代码  [![收藏代码](http://yufeng0471.iteye.com/images/icon_star.png)]()

1. 1   IDX\_T6\_STATUS   1

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

 

通过索引查询status值为'0'的数据

Sql代码  [![收藏代码](http://yufeng0471.iteye.com/images/icon_star.png)]()

1. select * from t6 where decode(status, '0', '0') = '0'

 执行计划如下

Sql代码  [![收藏代码](http://yufeng0471.iteye.com/images/icon_star.png)]()

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