SQL语句的优化

SQL语句在工作中必不可少,所有在实现功能的基础上进行优化是提升价值的关键所在。

1.在进行查询过程中,尽可能的避免全表扫描,并且考虑在where和order by所涉及的列建立索引。

SELECT * FROM customer WHERE name ='阿爆' ;

CREATE UNIQUE INDEX customer_name ON customer(name);--在customer表上的name列创建唯一性索引

2.避免在where关键词后使用!=,>,<操作符,否则会放弃索引而进行全表扫描。尽量避免在where子句中对字段进行null值判断,也会导致引擎放弃使用索引而进行全表扫描。

select id from student where num is null;

可以在num设置默认值为0,确保num中没有null值,这样查询:

select id from student where num = 0;

3.尽量避免在where子句中使用or来连接条件,否则引擎会放弃使用索引而进行全表扫描,如:

select id from student where num = 101 or num = 102;

可以这样查询:

select id from student where num = 101
union all
select id from student where num = 102;

union all允许列中相同的值出现在结果集中。

4.对于查询条件中的like,in,not in要慎用,会导致全表扫描,对于连续的数值能用between 就不用 in,使用like的全模糊(“%abc%”),是无法使用索引的:

#like
select id from student where name like "%abc%";
#in,not in
select id from student where num in (1,2,3);
#bewteen 
select id from student where num between 1 and 3;

5.在where子查询中使用参数,可能会导致全表扫描,因为只有sql在运行时才会解析局部变量,但优化程序不能将访问计划的选择推迟到运行时,必须在编译时进行选择。如果在编译时建立访问计划,变量的值还是未知的,所以无法作为索引选择的输入项。下面语句将进行全表扫描:

select id from student where num = @num;

可以改为强制查询使用索引:

select id from student with (index(索引名)) where num = @num;

 6.尽量避免对where的子句的字段进行表达式操作,会导致引擎放弃索引而对全表进行扫描:

select id from student where num/2 = 100;

改为

select id from  student where num = 100 *2;

7.尽量避免对where的子句的字段进行函数操作,会导致引擎放弃索引而对全表进行扫描

select id from student where Substring(name,1,3)="abc"     --name是以abc开头的字符串
select id from student where DateDiff(day,createdate,'2020-05-31')=0     --2020-05-31生成的id

改为

select id from student where name like 'abc%';
select id from student where createdate >= '2020-05-31' and createdate < '2020-06-01';

8.尽量不要在where子句的“=”左边进行函数,算术运算和其他表达式运算,否则系统可能无法正确使用索引。

9.如果使用的索引是复合索引的字段索引作为条件时,那么必须使用到该索的第一个字段作为条件时,才能保证系统使用该索引。而且尽可能的让字段的顺序和索引字段的顺序保持一致。

10.并不是所有的索引对查询都有效,SQL是根据表中的数据进行查询优化的。如果索引列有大量的数据重复时,SQL查询可能不会去利用索引查询,比如一表中的字段sex,male,female的字段各占一半,即使使用索引对sex进行查询,也对查询效率起不了作用。

11.索引不是越多越好,索引只是对select的查询效率有提升,同时也降低了updata,insert的效率,因为进行updata,insert时有可能会重建索引,所以如何建立索引要视情况而定,一个表的索引最好不要超过6个。

12.字符串类型选择尽量用varchar/nvarchar来代替char/nchar,因为变长字段存储空间小,可以减少存储空间,然后在一个相对较小的地段内搜索效率要高些。

13.不要使用select * from u,要用特定的字段来代替*,不要返回无用的字段信息。

14.尽量使用表变量来代替临时表,如果表变量中含有大量数据,注意索引非常有限(只有主键索引)。

posted @ 2020-06-09 17:16  会飞的猪、li  阅读(107)  评论(0编辑  收藏  举报