如
select id from employee where emp_id='8' (錯)
select id from employee where emp_id=8 (對)
emp_id是整數型,用'8'會默認啓動類型轉換,增加查詢的開銷。
4. 儘量減少使用正則表達式,儘量不使用通配符。
如:
select id from employee where UPPER(dept) like 'TECH_DB' (錯)
select id from employee where SUBSTR(dept,1,4)='TECH' (錯)
select id from employee where dept like 'TECH%' (對)
6.不要在字段上用轉換函數,儘量在常量上用
如:
select id from employee where to_char(create_date,'yyyy-mm-dd')='2012-10-31' (錯)
select id from employee where create_date=to_date('2012-10-31','yyyy-mm-dd') (對)
7.不使用聯接做查詢
如:select id from employee where first_name || last_name like 'Jo%' (錯)
8. 儘量避免前後都用通配符
如:
select id from employee where dept like '%TECH%' (錯)
select id from employee where dept like 'TECH%' (對)
如:
select id from employee where creat_date-30>to_date('2012-10-31','yyyy-mm-dd') (錯)
select id from employee where creat_date >to_date('2012-10-31','yyyy-mm-dd')+30 (對)
10. 儘量使用exists而非in
當然這個也要根據記錄的情況來定用exists還是用in, 通常的情況是用exists
select id from employee where salary in (select salary from emp_level where....) (錯)
select id from employee where salary exists(select 'X' from emp_level where ....) (對)
11. 使用not exists 而非not in
和上面的類似
12. 減少查詢表的記錄數範圍
索引可以提高速度,一般來說,選擇度越高,索引的效率越高。
14. 索引類型
唯一索引,對於查詢用到的字段,儘可能使用唯一索引。
還有一些其他類型,如位圖索引,在性別字段,只有男女的字段上用。
如:
select id from employee where emp_name like '%%' (錯)
20. 儘量對經常用作group by的關鍵字段做索引。
利用外連接替換效率十分低下的not in運算,大大提高運行速度。
如:
select a.id from employee a where a.emp_no not in (select emp_no from employee1 where job ='SALE') (錯)
22. 使用臨時表
在必要的情況下,爲減少讀取次數,可以使用經過索引的臨時表加快速度。
如:
select e.id from employee e ,dept d where e.dept_id=d.id and e.empno>1000 order by e.id (錯)
select id,empno from employee into temp_empl where empno>1000 order by id
select m.id from temp_emp1 m,dept d where m.empno=d.id (對)
對於大數據量sql語句性能優化更多的工作就交給dba去實踐,我們程序員做好這些基本功就好了。