
索引能够消除排序,但是如果排序是部分升序部分降序,就必须建对应部分升降序的索引,否则无法用这个来消除排序。比如order by col1 desc col2 asc,我们可以建(col1 desc,col2 asc)的索引。
请注意,如果你的语句变成 order by col1 asc col2 desc,之前的(col1 desc,col2 asc)的索引依然可以起到避免排序的作用DESCING,不要为此多建无意义的索引。
以下通过案例说明。
构建环境
创建测试表:
SQL> drop table t purge;
SQL> create table t as select * from dba_objects where object_id is not null ;
SQL> insert into t select * from t;
SQL> insert into t select * from t;
SQL> commit;
创建索引:
SQL> create index idx_t on t (owner,object_id);
SQL> alter table t modify owner not null;
SQL> alter table t modify object_id not null;
SQL> set linesize 1000
SQL> set autotrace traceonly
order by 列有索引可以消除排序,但是下面的例子,Oracle没有使用索引,排序依然存在:
SQL> select * from t a order by owner desc ,object_type asc;
执行计划:
order by 部分升序,部分降序,无法消除排序。
想要消除排序,建立如下索引:
SQL> create index idx_t on t(owner desc,object_type asc);
执行计划:







