8. 使用decode函數來減少處理時間
使用decode函數可以避免重復掃描相同記錄或重復連接相同的表.
例如:
select count(*),sum(sal)
from emp
where dept_no = 0020
and ename like ‘smith%’;
select count(*),sum(sal)
from emp
where dept_no = 0030
and ename like ‘smith%’;
你可以用decode函數高效地得到相同結果
select count(decode(dept_no,0020,’x’,null)) d0020_count,
count(decode(dept_no,0030,’x’,null)) d0030_count,
sum(decode(dept_no,0020,sal,null)) d0020_sal,
sum(decode(dept_no,0030,sal,null)) d0030_sal
from emp where ename like ‘smith%’;
類似的,decode函數也可以運用于group by 和order by子句中.
9. 整合簡單,無關聯的數據庫訪問
如果你有幾個簡單的數據庫查詢語句,你可以把它們整合到一個查詢中(即使它們之間沒有關系)
例如:
select name
from emp
where emp_no = 1234;
select name
from dpt
where dpt_no = 10 ;
select name
from cat
where cat_type = ‘rd’;
上面的3個查詢可以被合并成一個:
select e.name , d.name , c.name
from cat c , dpt d , emp e,dual x
where nvl(‘x’,x.dummy) = nvl(‘x’,e.rowid(+))
and nvl(‘x’,x.dummy) = nvl(‘x’,d.rowid(+))
and nvl(‘x’,x.dummy) = nvl(‘x’,c.rowid(+))
and e.emp_no(+) = 1234
and d.dept_no(+) = 10
and c.cat_type(+) = ‘rd’;
(譯者按: 雖然采取這種方法,效率得到提高,但是程序的可讀性大大降低,所以讀者 還是要權衡之間的利弊)
10. 刪除重復記錄
最高效的刪除重復記錄方法 ( 因為使用了rowid)
delete from emp e
where e.rowid > (select min(x.rowid)
from emp x
where x.emp_no = e.emp_no);
11. 用truncate替代delete
當刪除表中的記錄時,在通常情況下, 回滾段(rollback segments ) 用來存放可以被恢復的信息. 如果你沒有commit事務,oracle會將數據恢復到刪除之前的狀態(準確地說是
恢復到執行刪除命令之前的狀況)
而當運用truncate時, 回滾段不再存放任何可被恢復的信息.當命令運行后,數據不能被恢復.因此很少的資源被調用,執行時間也會很短.
(譯者按: truncate只在刪除全表適用,truncate是ddl不是dml)
12. 盡量多使用commit
只要有可能,在程序中盡量多使用commit, 這樣程序的性能得到提高,需求也會因為commit所釋放的資源而減少:
commit所釋放的資源:
a. 回滾段上用于恢復數據的信息.
b. 被程序語句獲得的鎖
c. redo log buffer 中的空間
d. oracle為管理上述3種資源中的內部花費
(譯者按: 在使用commit時必須要注意到事務的完整性,現實中效率和事務完整性往往是魚和熊掌不可得兼)