本文來源于網(wǎng)頁設(shè)計愛好者web開發(fā)社區(qū)http://www.html.org.cn收集整理,歡迎訪問。
31. 強制索引失效
如果兩個或以上索引具有相同的等級,你可以強制命令oracle優(yōu)化器使用其中的一個(通過它,檢索出的記錄數(shù)量少) .
舉例:
select ename
from emp
where empno = 7935
and deptno + 0 = 10 /*deptno上的索引將失效*/
and emp_type || ‘’ = ‘a(chǎn)’ /*emp_type上的索引將失效*/
這是一種相當直接的提高查詢效率的辦法. 但是你必須謹慎考慮這種策略,一般來說,只有在你希望單獨優(yōu)化幾個sql時才能采用它.
這里有一個例子關(guān)于何時采用這種策略,
假設(shè)在emp表的emp_type列上有一個非唯一性的索引而emp_class上沒有索引.
select ename
from emp
where emp_type = ‘a(chǎn)’
and emp_class = ‘x’;
優(yōu)化器會注意到emp_type上的索引并使用它. 這是目前唯一的選擇. 如果,一段時間以后, 另一個非唯一性建立在emp_class上,優(yōu)化器必須對兩個索引進行選擇,在通常情況下,優(yōu)化器將使用兩個索引并在他們的結(jié)果集合上執(zhí)行排序及合并. 然而,如果其中一個索引(emp_type)接近于唯一性而另一個索引(emp_class)上有幾千個重復(fù)的值. 排序及合并就會成為一種不必要的負擔(dān). 在這種情況下,你希望使優(yōu)化器屏蔽掉emp_class索引.
用下面的方案就可以解決問題.
select ename
from emp
where emp_type = ‘a(chǎn)’
and emp_class||’’ = ‘x’;
32. 避免在索引列上使用計算.
where子句中,如果索引列是函數(shù)的一部分.優(yōu)化器將不使用索引而使用全表掃描.
舉例:
低效:
select …
from dept
where sal * 12 > 25000;
高效:
select …
from dept
where sal > 25000/12;
譯者按:
這是一個非常實用的規(guī)則,請務(wù)必牢記
33. 自動選擇索引
如果表中有兩個以上(包括兩個)索引,其中有一個唯一性索引,而其他是非唯一性.
在這種情況下,oracle將使用唯一性索引而完全忽略非唯一性索引.
舉例:
select ename
from emp
where empno = 2326
and deptno = 20 ;
這里,只有empno上的索引是唯一性的,所以empno索引將用來檢索記錄.
table access by rowid on emp
index unique scan on emp_no_idx
34. 避免在索引列上使用not
通常, 我們要避免在索引列上使用not, not會產(chǎn)生在和在索引列上使用函數(shù)相同的
影響. 當oracle”遇到”not,他就會停止使用索引轉(zhuǎn)而執(zhí)行全表掃描.
舉例:
低效: (這里,不使用索引)
select …
from dept
where dept_code not = 0;
高效: (這里,使用了索引)
select …
from dept
where dept_code > 0;
需要注意的是,在某些時候, oracle優(yōu)化器會自動將not轉(zhuǎn)化成相對應(yīng)的關(guān)系操作符.
not > to <=
not >= to <
not < to >=
not <= to >
譯者按:
在這個例子中,作者犯了一些錯誤. 例子中的低效率sql是不能被執(zhí)行的.
我做了一些測試:
sql> select * from emp where not empno > 1;
no rows selected
execution plan
----------------------------------------------------------
0 select statement optimizer=choose
1 0 table access (by index rowid) of 'emp'
2 1 index (range scan) of 'empno' (unique)
sql> select * from emp where empno <= 1;
no rows selected
execution plan
----------------------------------------------------------
0 select statement optimizer=choose
1 0 table access (by index rowid) of 'emp'
2 1 index (range scan) of 'empno' (unique)
兩者的效率完全一樣,也許這符合作者關(guān)于” 在某些時候, oracle優(yōu)化器會自動將not轉(zhuǎn)化成相對應(yīng)的關(guān)系操作符” 的觀點.
35. 用>=替代>
如果deptno上有一個索引,
高效:
select *
from emp
where deptno >=4
低效:
select *
from emp
where deptno >3
兩者的區(qū)別在于, 前者dbms將直接跳到第一個dept等于4的記錄而后者將首先定位到deptno=3的記錄并且向前掃描到第一個dept大于3的記錄.