sql常用的優化技巧

2021-08-22 10:13:01 字數 2915 閱讀 5830

一,通過變數的方式來設定引數

好: stringsql = 「select * from people p where p.id = ? 「;

壞: stringsql = 「select * from people p where p.id = 「+id;

資料庫的sql文解析和執行計畫會儲存在快取中,但是sql文只要有變化,就得重新解析。

「…where p.id = 」+id的方式在id值發生改變時需要重新解析,這會耗費時間。

二,不要使用select *

好: stringsql = 「select people_name,pepole_age from people 「;

壞: stringsql = 「select * from people 「;

使用select *的話會增加解析的時間,另外會把不需要的資料也給查詢出來,資料傳輸也是耗費時間的,

比如text型別的字段通常用來儲存一些內容比較繁雜的東西,如果使用select *則會把該字段也查詢出來。

三,謹慎使用模糊查詢

好: stringsql = 「select * from people p where p.id like 『parm1%』 「;

壞: stringsql = 「select * from people p where p.id like 『%parm1%』 「;

當模糊匹配以%開頭時,該列索引將失效,若不以%開頭,該列索引有效

四,不要使用列號

好: stringsql = 「select people_name,pepole_age from people order by name,age」;

壞: stringsql = 「select people_name,pepole_age from people order by 6,8」;

使用列號的話,將會增加不必要的解析時間。

五,優先使用union all,避免使用union

好: stringsql = 「select name from student union all select name from teacher」;

壞: stringsql = 「select name from student union select name from teacher」;

union 因為會將各查詢子集的記錄做比較,故比起union all ,通常速度都會慢上許多。一般來說,如果使用union all能滿足要求的話,務必使用union all。還有一種情況,如果業務上能夠確保不會出現重覆記錄。

六,在where語句或者order by語句中避免對索引字段進行計算操作

好: stringsql = 「select people_name,pepole_age from people where create_date=date1 「;

壞: stringsql = 「select people_name,pepole_age from people where trunc(create_date)=date1」;

當在索引列上進行操作之後,索引將會失效。正確做法應該是將值計算好再傳入進來。

七,使用not exist代替not in

好: stringsql = 「select * from orders where customer_name not exist (select customer_name from customer)」;

壞: stringsql = 「select * from orders where customer_name not in(select customer_name from customer)」;

如果查詢語句使用了not in 那麼內外表都進行全表掃瞄,沒有用到索引;而not extsts 的子查詢依然能用到表上的索引。

八,exist和in的區別

in 是把外表和內錶作hash 連線,而exists是對外表作loop迴圈,每次loop迴圈再對內表進行查詢。因此,in用到的是外表的索引, exists用到的是內錶的索引。

如果查詢的兩個表大小相當,那麼用in和exists差別不大。

如果兩個表中乙個較小,乙個是大表,則子查詢表大的用exists,子查詢錶小的用in:

例如:表a(小表),表b(大表)

1: select * from a where cc in (select cc from b)

效率低,用到了a表上cc列的索引;

select * from a where exists(select cc from b where cc=a.cc)

效率高,用到了b表上cc列的索引。

2:select * from b where cc in (select cc from a)

效率高,用到了b表上cc列的索引;

select * from b where exists(select cc from a where cc=b.cc)

效率低,用到了a表上cc列的索引。

九,避免在索引列上做如下操作:

◆避免在索引欄位上使用<>,!=

◆避免在索引列上使用is null和is not null

◆避免在索引列上出現資料型別轉換(比如某字段是string型別,引數傳入時是int型別)

當在索引列上使用如上操作時,索引將會失效,造成全表掃瞄。

十,複雜操作可以考慮適當拆成幾步

有時候會有通過乙個sql語句來實現複雜業務的例子出現,為了實現複雜的業務,巢狀多級子查詢。造成sql效能問題。對於這種情況可以考慮拆分sql,通過多個sql語句實現,或者把部分程式能完成的工作交給程式完成。

常用SQL優化技巧

作為程式設計師經常和資料庫打交道的時候還是非常頻繁的,掌握住一些sql的優化技巧還是非常有必要的。下面列出一些常用的sql優化技巧,感興趣的朋友可以了解一下。1 注意萬用字元中like的使用 以下寫法會造成全表的掃瞄,例如 select id,name from userinfo where nam...

常用SQL語句優化技巧

除了建立索引之外,保持良好的sql語句編寫習慣將會降低sql效能問題發生。通過變數的方式來設定引數 好 stringsql select from people p where p.id 壞 stringsql select from people p where p.id id 資料庫的sql文解...

常用的7個SQl優化技巧

作為程式設計師經常和資料庫打交道的時候還是非常頻繁的,掌握住一些sql的優化技巧還是非常有必要的。下面列出一些常用的sql優化技巧,感興趣的朋友可以了解一下。1 注意萬用字元中like的使用 以下寫法會造成全表的掃瞄,例如 select id,name from userinfo where nam...