sql语句提高数据库查询效率
可以通過以下多個方面優化sql語句提高數據庫查詢效率
1. 應盡量避免在 where 子句中使用!=或<>操作符,否則將引擎放棄使用索引而進行全表掃描。
2. 應盡量避免在 where 子句中使用 or 來連接條件,否則將導致引擎放棄使用索引而進行全表掃描,如: select id from t where num=10 or num=20 可以這樣查詢: select id from t where num=10 union all select id from t where num=20
3. in 和 not in 也要慎用,否則會導致全表掃描,如: select id from t where num in(1,2,3) 對于連續的數值,能用 between 就不要用 in 了: select id from t where num between 1 and 3
4. 下面的查詢也將導致全表掃描: select id from t where name like ‘%abc%’
5. 如果在 where 子句中使用參數,也會導致全表掃描。因為SQL只有在運行時才會解析局部變量,但優化程序不能將訪問計劃的選擇推遲到運行時;它必須在編譯時進行選擇。然而,如果在編譯時建立訪問計劃,變量的值還是未知的,因而無法作為索引選擇的輸入項。如下面語句將進行全表掃描: select id from t where num=@num 可以改為強制查詢使用索引: select id from t with(index(索引名)) where num=@num
6. 應盡量避免在 where 子句中對字段進行表達式操作,這將導致引擎放棄使用索引而進行全表掃描。如: select id from t where num/2=100 應改為: select id from t where num=100*2
7. 應盡量避免在where子句中對字段進行函數操作,這將導致引擎放棄使用索引而進行全表掃描。如: select id from t where substring(name,1,3)=’abc’–name以abc開頭的id select id from t where datediff(day,createdate,’2005-11-30′)=0–‘2005-11-30’生成的id 應改為: select id from t where name like ‘abc%’ select id from t where createdate>=’2005-11-30′ and createdate<’2005-12-1′
8 不要在 where 子句中的“=”左邊進行函數、算術運算或其他表達式運算,否則系統將可能無法正確使用索引。
9. 不要寫一些沒有意義的查詢,如需要生成一個空表結構: select col1,col2 into #t from t where 1=0 這類代碼不會返回任何結果集,但是會消耗系統資源的,應改成這樣: create table #t(…)
10. 很多時候用 exists 代替 in 是一個好的選擇: select num from a where num in(select num from b) 用下面的語句替換: select num from a where exists(select 1 from b where num=a.num)
11. 任何地方都不要使用 select * from t ,用具體的字段列表代替“*”,不要返回用不到的任何字段。
12. 盡量避免使用游標,因為游標的效率較差,如果游標操作的數據超過1萬行,那么就應該考慮改寫。
13. 盡量避免向客戶端返回大數據量,若數據量過大,應該考慮相應需求是否合理。
14. 盡量避免大事務操作,提高系統并發能力。
總結
以上是生活随笔為你收集整理的sql语句提高数据库查询效率的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 序列化 protobuf_ja
- 下一篇: SQL触发器demo