作為程式設計師經常和資料庫打交道的時候還是非常頻繁的,掌握住一些sql的優化技巧還是非常有必要的。下面列出一些常用的sql優化技巧,感興趣的朋友可以了解一下。
1、注意萬用字元中like的使用
以下寫法會造成全表的掃瞄,例如:
select id,name from userinfo where name like '%name%'
或者select id,name from userinfo where name like '%name'
下面的寫法執行效率快很多,因為它使用了索引
select id,name from userinfo where name like 'name%'
2、避免在where子句中對字段進行函式操作
比如:select id from userinfo where substring(name,1,6) = 'xiaomi'
或者select id from userinfo where datediff(day,datefield,'2017-05-17') >= 0
上面兩句都對字段進行了函式處理,會導致查詢分析器放棄了索引的使用。
正確的寫法:
select id from userinfo where name like'xiaomi%'
select id from userinfo where datefield <= '2017-05-17'
通俗理解就是where子句『=』 左邊不要出現函式、算數運算或者其他表示式運算
3、在子查詢當中,盡量用exists代替in
select name from userinfo a where id in(select id from userinfo b)
可以改為
select name from userinfo a where exists(select 1 from userinfo b where id = a.id)
下面的查詢速度比in查詢的要快很多。
4、where子句中盡量不要使用is null 或 is not null對欄位進行判斷
例如:select id from userinfo where name is null
盡量在資料庫欄位中不出現null,如果查詢的時候條件為 is null ,索引將不會被使用,造成查詢效率低,
因此資料庫在設計的時候,盡可能將某個字段可能為空的時候設定預設值,那麼查詢的時候可以
根據預設值進行查詢,比如name欄位設定為0,查詢語句可以修改為
select id from userinfo where name=0
5、避免在where子句使用or作為鏈結條件
例如:select id from userinfo where name='xiaoming' or name='xiaowang'
可以改寫為:
select id from userinfo where name = 'xiaoming' union all
select id from userinfo where name = 'xiaowang'
6、避免在 where 子句中使用 != 或 <> 操作符。
例如:select name from userinfo where id <> 0
說明:資料庫在查詢時,對 != 或 <> 操作符不會使用索引,
而對於 < 、 <= 、 = 、 > 、 >= 、 between and,資料庫才會使用索引。
因此對於上面的查詢,正確寫法可以改為:
select name from userinfo where id < 0 union all
select name from userinfo where id > 0
7、少用in 或 not in
對於連續的數值範圍查詢盡量使用between and,例如:
select name from userinfo where id between 10 and 70
以上只是相對來說比較常用的sql優化技巧,當然還有很多歡迎補充!
sql常用的優化技巧
一,通過變數的方式來設定引數 好 stringsql select from people p where p.id 壞 stringsql select from people p where p.id id 資料庫的sql文解析和執行計畫會儲存在快取中,但是sql文只要有變化,就得重新解析。wh...
常用SQL語句優化技巧
除了建立索引之外,保持良好的sql語句編寫習慣將會降低sql效能問題發生。通過變數的方式來設定引數 好 stringsql select from people p where p.id 壞 stringsql select from people p where p.id id 資料庫的sql文解...
sql優化技巧
1.比較運算子能用 就不用 增加了索引的使用機率 2.事先知道只有一條查詢結果時,使用 limit 1 limit 1 可以避免全表掃瞄,找到對應結果就不會再繼續掃瞄了 3.選擇合適的資料型別很重要 能用tinyint就不用smallint,能用smallint就不用int,磁碟和記憶體消耗越小越好...