sqlserver 优化

避免在索引列上使用计算

where子句中,如果索引列是函数的一部分,优化器将不使用索引而使用全表扫描。例如:

(低效)select ... from [dept] where [sal]*12>25000;

(高效)select ... from [dept] where [sal]>25000/12;

--------------
不同类型的索引效能是不一样的,应尽可能先使用效能高的

数字类型的索引查找效率高于字符串类型,定长字符串char、nchar的索引效率高于变长字符串varchar、nvarchar的索引。

(低效)select ... from tableName where username='张三' and age>=21

(高效)select ... from tableName where age>=21 and username='张三'
------------------------------------
使用exists或not exists代替in或not in

(高效)select * from [emp] where [empno]>0 and exists (select 'X' from [dept] where [dept].[deptno]=[emp].[deptno] and [loc]='MELB');

(低效)select * from [emp] where [empno]>0 and [deptno] in (select [deptno] from [dept] where [loc]='MELB');
----------------------------------------------------
is null或is not null操作

判断字段是否为空一般是不会应用索引的,因为索引不索引空值。不能用null作索引,任何包含null值的列都将不会被包含在索引中。也就是说如果某列存在空值,即使对该列建索引也不会提高性能。任何在where子句中使用
is null或is not null的语句优化器都不允许使用索引。

推荐方案:用其他相同功能的操作运算代替,如:a is not null改为a>0或a>''等。
---------------------------------------------------------------------------
<及>操作

大于或小于一般情况不用调整,因为它有索引就会采用索引查找,但有的情况下可以对它进行优化。如一个表有100万记录,那么执行>2与>=3的效果就有很大区别了。

(低效)select * from [emp] where [deptno]>2;

(高效)select * from [emp] where [deptno]>=3;
----------------------------------------------------------

原文地址:https://www.cnblogs.com/mmbbflyer/p/7677862.html