当前位置: 移动技术网 > IT编程>数据库>Oracle > 关于oracle order by索引是否使用的情况实例讲解

关于oracle order by索引是否使用的情况实例讲解

2018年09月12日  | 移动技术网IT编程  | 我要评论

福州房屋出租,熊井友理奈种子,深圳人才市场地址

刚开始在网上看了很多说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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网