oracle order by索引是否使用的情况

前端之家收集整理的这篇文章主要介绍了oracle order by索引是否使用的情况前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

刚开始在网上看了很多说order by 走索引有两个前提条件

1,ORDER BY中所有的列必须包含在相同的索引中并保持在索引中的排列顺序.

2,ORDER BY中所有的列必须定义为非空.

下面是测试:

建表:

create table person ( id VARCHAR2(50) not null,name VARCHAR2(20) not null,phone VARCHAR2(11) not null,time TIMESTAMP(6) not null ) 

创建索引

create index index_person on person(time,phone);

执行语句测试:

1,

select * from person where 1=1 and time <= to_date('2013-12-12 12:12:12','yyyy-MM-dd hh24:mi:ss') and phone = '13892441321' order by time desc --使用索引 

2,

select * from person order by time desc --不使用索引 

这个有个特别的情况:

1,

select * from person where 1=1 and phone = '13892441321' order by time desc --使用索引 

2,

select * from person where 1=1 and phone = '13892441321' --不使用索引 

这种情况是加了个order by time才使用了索引,我的理解是只有一个条件phone的时候索引无效,加了order by time,才用到了索引

分页的时候使用索引,例如:
1,

select * from person order by time desc --不使用索引 

2,

select * from ( select * from person order by time desc) --这里换成order by phone也是不走索引的,这个是索引的前缀原则。 where rownum <=1000 --使用索引 

总结:其实order by 满足以上的两个条件后,决定走不走索引的还要看where后面的条件,先要where条件符合,走了索引才行。上面的第二条没加条件,显然是不使用索引的。很多时候建立索引要看具体业务需求,也就是查询条件。走不走索引,主要是测试一下,看看执行计划。

假如一定要对使用函数的列启用索引,ORACLE新的功能: 基于函数的索引(Function-Based Index) 也许是一个较好的方案.

CREATE INDEX EMP_I ON EMP (UPPER(ename)); /*建立基于函数的索引*/

     SELECT * FROM emp WHERE UPPER(ename) = ‘BLACKSNAIL'; /*将使用索引*/   

5 怎样监控无用的索引   

Oracle 9i以上,可以监控索引的使用情况,假如一段时间内没有使用的索引,一般就是无用的索引   

语法为:   

开始监控:alter index index_name monitoring usage;

 检查使用状态:select * from v$object_usage; 

 停止监控:alter index index_name nomonitoring usage;   

当然,假如想监控整个用户下的索引,可以采用如下的脚本:

set heading off set echo off set Feedback off set pages 10000 spool start_index_monitor.sql SELECT 'alter index 'owner'.'index_name' monitoring usage;' FROM dba_indexes WHERE owner = USER; spool off set heading on set echo on set Feedback on set heading off set echo off set Feedback off set pages 10000 spool stop_index_monitor.sql SELECT 'alter index 'owner'.'index_name' nomonitoring usage;' FROM dba_indexes WHERE owner = USER; spool off set heading on set echo on set Feedback on

其实最好的办法是查看执行计划。

原文链接:https://www.f2er.com/oracle/206143.html

猜你在找的Oracle相关文章