---
title: "oracle 索引"
author: "hougbin"
date: "2010-12-30T09:34:04Z"
tags: ["Blog", "HTML", "Oracle", "SQL"]
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2010-12-30T09:34:04Z"
id: 855431
url: "https://hougbin.iteye.com/blog/855431"
---

索引分类：

- 唯一索引，作用是数据约束，保证数据唯一，还有就是数据索引，提高查询效率
- 一般索引，只有数据索引的作用。

唯一索引：

Sql代码 [![复制代码](http://desert3.iteye.com/images/icon_copy.gif)](http://desert3.iteye.com/blog/784644 "复制代码")

1. **create** **unique** **index** idx\_employee\_empname **on** employee(empname);

```
create unique index idx_employee_empname on employee(empname);
```

一般索引：

Sql代码 [![复制代码](http://desert3.iteye.com/images/icon_copy.gif)](http://desert3.iteye.com/blog/784644 "复制代码")

1. **create** **index** idx\_employee\_address **on** employee(address);
2. **create** **unique** **index** idx\_employee\_field1\_field2 **on** employee(field1,field2);

```
create index idx_employee_address on employee(address);
create unique index idx_employee_field1_field2 on employee(field1,field2);
```

函数索引：

Sql代码 [![复制代码](http://desert3.iteye.com/images/icon_copy.gif)](http://desert3.iteye.com/blog/784644 "复制代码")

1. **create** **index** idx\_product\_nvl\_price **on** product(nvl(price,0.0));

```
create index idx_product_nvl_price on product(nvl(price,0.0));
```

删除索引：

Sql代码 [![复制代码](http://desert3.iteye.com/images/icon_copy.gif)](http://desert3.iteye.com/blog/784644 "复制代码")

1. **drop** **index** idx\_employee\_empname;

```
drop index idx_employee_empname;
```

指定索引表空间

Sql代码 [![复制代码](http://desert3.iteye.com/images/icon_copy.gif)](http://desert3.iteye.com/blog/784644 "复制代码")

1. **create** **index** idx\_employee\_address **on** employee(address) tablespace indexs;

```
create index idx_employee_address on employee(address) tablespace indexs;
```

查看索引

Sql代码 [![复制代码](http://desert3.iteye.com/images/icon_copy.gif)](http://desert3.iteye.com/blog/784644 "复制代码")

1. **select** * **from** user\_indexes **where** table\_name = 'SHOP\_PD'

```
select * from user_indexes where table_name = 'SHOP_PD'
```

参考：  
[http://www.java2s.com/Tutorial/Oracle/0180\_\_Index/Createindexwithtablespace.htm](http://www.java2s.com/Tutorial/Oracle/0180__Index/Createindexwithtablespace.htm)  
[http://hi.baidu.com/luodaijun/blog/item/2ea274f065c856aea50f5219.html](http://hi.baidu.com/luodaijun/blog/item/2ea274f065c856aea50f5219.html)

以下情况下索引会失效

- 查询条件中字段使用顺序和组合索引定义中字段的顺序不一致时，索引无效oracle 10这种情况下索引已经起作用，低版本的不起作用
- 使用!=,&lt;&gt;操作符会限制索引，换成 &gt; or &lt; 不会oracle 10这种情况下索引已经起作用，低版本的不起作用
- 对索引列使用函数会忽略索引必要的情况下，可以建立函数索引
- 试着对被SUM，MAX，MIN的列增加索引

有时候索引不起作用是因为oralce在使用基于成本的优化器（CBO），走索引的代价反而更加高，使得sql走全表扫描，可以如下使用强制索引语法，然后查看执行计划中的消耗

Sql代码 [![复制代码](http://desert3.iteye.com/images/icon_copy.gif)](http://desert3.iteye.com/blog/784644 "复制代码")

1. **select** /\*+ **index**(t,IDX\_AR\_JDXX\_SELL)\*/t.province, t.city, t.country
2. **from** ar\_sell t
3. **group** **by** t.type\_code,t.province, t.city, t.country