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