sql优化的方法总结
1.對查詢進行優化,應該盡量避免全表掃描,首先應考慮在where和order by涉及的列上建立索引
2.應盡量避免在where子句中使用!=或<>操作符,否則將引擎放棄使用索引而進行全表掃描
3.應盡量避免在where子句中對字段進行null值判斷,否則將導致引擎放棄使用索引而進行全表掃描,如:
select id from t where num is null
可以在num上設置默認值0,確保表中num列沒有null值,然后這樣查詢:
select id from t where num=0
4.盡量避免在where子句中使用or來連接條件,否則將導致引擎放棄使用索引而進行全表掃描,如:
selec id from t where num=10 or num=20
改成這樣查詢:
select id from where num=10 union all select id from t where num=20
5.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
6.如果在where子句中使用參數,也會導致全表掃描。如:
select id from t where num=@num
可以改成強制查詢使用索引
select id from t with(index(索引名)) where num=@num
7.避免在where子句中隊字段進行表達式操作,否則導致全表掃描:
select id from t where num/2=100
應改為:select id from t where num=100*2
8.不要再 where子句中的'='左邊進行函數,算數運算或其他表達式運算,否則系統將無法正確使用索引
9.需要的話用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)
10.盡可能的使用varchar/nvarchar代替char/nchar,因為首先變長字段存儲空間小,可以節省存儲空間。對于存儲空間小的,查詢會效率更高。
11.任何地方都不要使用select * from t ,用具體的字段列表代替'*',不要返回用不到的任何字段
12.盡量使用表變量來代替臨時表,如果表變量包含大量數據請注意索引非常有限(只有主鍵索引)
13.避免頻繁創建和刪除臨時表,以減少系統資源的消耗
14.在新建臨時表的時候,如果一次性插入數據量大,可以使用insert into 代替create table。否則優先用create table
15.如果使用到了臨時表,在存儲過程的最后,務必將所有的臨時表顯式刪除,先truncate table,在drop table
轉載于:https://www.cnblogs.com/chaofei/p/7683708.html
總結
以上是生活随笔為你收集整理的sql优化的方法总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MAC OS Sierra 10.12.
- 下一篇: Codeforces Round #43