CBO参数之一“_sort_elimination_cost_ratio”
[sql]
create table t1 as select * from dba_objects where object_id is not null;
alter table t1 add constraint t1_pk primary key(object_id);
create index t1_ind on t1(object_type);
alter session set optimizer_mode=first_rows;
alter session set "_sort_elimination_cost_ratio" = 0;
以上脚本创建了一张表,表的主键是object_id,表上有一个普通索引object_type.
set autotrace traceonly
select *
2 from t1
3 where object_type = 'TABLE'
4 order by
5 object_id
6 ;
2060 rows selected.
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT ptimizer=FIRST_ROWS (Cost=276 Card=423 Bytes=36378)
1 0 TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=276 Card=423 Bytes=36378)
2 1 INDEX (FULL SCAN) OF 'T1_PK' (UNIQUE) (Cost=23 Card=10986)
我们看到默认的执行计划走了主键索引的index full scan.算出来的cost是276.
select /*+ no_index(t1,t1_pk) */
2 *
3 from t1
4 where object_type = 'TABLE'
5 order by
6 object_id
7 ;
2060 rows selected.
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT ptimizer=FIRST_ROWS (Cost=46 Card=423 Bytes=36378)
1 0 SORT (ORDER BY) (Cost=46 Card=423 Bytes=36378)
2 1 TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=32 Card=423Bytes=36378)
3 2 INDEX (RANGE SCAN) OF 'T1_IND' (NON-UNIQUE) (Cost=1 Card=423)
通过为语句增加hint的方式,查询计划走了index RANGE scan.这个时候的cost是46.
select 276/46 from dual;
276/46
----------
6
默认的查询计划(INDEX pk full scan)的cost是走object_type索引查询计划的6倍。
我们通过设置_sort_elimination_cost_ratio的值小于6,准确点说,小于6大于0的整数都可以。
alter session set "_sort_elimination_cost_ratio" =5;
Session altered.
select
2 *
3 from t1
4 where object_type = 'TABLE'
5 order by
6 object_id
7 ;
2060 rows selected.
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT ptimizer=FIRST_ROWS (Cost=46 Card=423 Bytes=36378)
1 0 SORT (ORDER BY) (Cost=46 Card=423 Bytes=36378)
2 1 TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=32 Card=423Bytes=36378)
3 2 INDEX (RANGE SCAN) OF 'T1_IND' (NON-UNIQUE) (Cost=1 Card=423)
可以看到默认的执行计划已经走到了object_type索引的range scan.
如果设置参数_sort_elimination_cost_ratio的值大于6,那么查询计划依然会走主键列的index full scan.
alter session set "_sort_elimination_cost_ratio" =6/7(只要大等于6);
Session altered.
select
*
from t1
where object_type = 'TABLE'
order by
object_id
;
2060 rows selected.
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT ptimizer=FIRST_ROWS (Cost=276 Card=423 Bytes=36378)
1 0 TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=276 Card=423 Bytes=36378)
2 1 INDEX (FULL SCAN) OF 'T1_PK' (UNIQUE) (Cost=23 Card=10986)
可以看到 _sort_elimination_cost_ratio 的含义。
如果不走排序的成本/走排序的成本 > _sort_elimination_cost_ratio.那么执行计划会走排序。
如果不走排序的成本/走排序的成本 < _sort_elimination_cost_ratio.那么执行计划不会走排序。
_sort_elimination_cost_ratio=0是一个比较特殊的值,代表任何时候都要消减排序,即使排序的成本的是无穷大。
如果想取消这个特性,那么就把这个参数值设置成1。