SQL优化的总结和一些避免全盘扫描的注意事项

1.应尽量避免在 where 子句中使用 != 或 <> 操作符,否则将引擎放弃使用索引而进行全表扫描。

2.应尽量避免在 where 子句中使用 or 来连接条件,如果一个字段有索引,一个字段没有索引,将导致引擎放弃使用索引而进行全表扫描

可以考虑用union

select id from t where num=10 or Name = 'admin' 

可以替换为

select id from t where num = 10

union all

select id from t where Name = 'admin'

3. in  和 not in 也要慎用,否则会导致全表扫描,可以用 exists 代替 in

select id from t where num in(1,2,3)

可以替换为

select id from t where num between 1 and 3

4.如果在 where 子句中使用参数,也会导致全表扫描。

select id from t where num = @num (bad !!!)

5.避免在 where 子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描

select id from t where num/2 = 100

应该为

select id from t where num = 100*2

6.应尽量避免在where子句中对字段进行函数操作

select id from t where substring(name,1,3) = ’abc’

应改为

select id from t where name like 'abc%'

7.Update 语句,如果只更改1、2个字段,不要Update全部字段,否则频繁调用会引起明显的性能消耗

8.尽量使用数字型字段,若只含数值信息的字段尽量不要设计为字符型,这会降低查询和连接的性能,并会增加存储开销。这是因为引擎在 处 理查询和连 接时会逐个比较字符串中每一个字符,而对于数字型而言只需要比较一次就够了。

9.尽可能的使用 varchar/nvarchar 代替 char/nchar,因为首先varchar是一个变长的字段, 变长字段存储空间小,

可以节省存储空间,其次对于查询来说,在一个相对较小的字段内搜索效率显然要高些。

10.删除JOIN和WHERE子句中的计算字段

SELECT * FROM sales a 

JOIN budget b ON ((YEAR(a.sale_date)* 100) + MONTH(a.sale_date)) = b.budget_year_month

应改为

SELECT * FROM PRODUCTSFROM sales a 

JOIN budget b ON a.sale_year_month = b.budget_year_month

原文地址:https://www.cnblogs.com/lingtiaoti/p/11726860.html