sql 优化点

文档:https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-depends-transact-sql?view=sql-server-ver16

sp_depends [table A] :可以查到所有用到表A的SP的

sp_helptext [sp name] :可以查SP的逻辑sql

参考:https://www.51cto.com/article/623584.html

一、sql优化:

1.最大化利用索引,尽量避免非索引查询,索引查询基本是精确查询,使用时避免用like、in、not in、exists、distinct等关键字。

2.尽可能避免全表扫描

3.减少无效数据、字段的查询,避免select * from [table A]

二、非索引查询

1.Distinct :会造成全表扫描,慎用

2.like:通配符查询,用的不好会有性能问题,如:like '%5400%' 不会用索引,而 like 'x5400%' 会引用全范围比对查找

3.in、not in:效率低,不推荐,推荐用exists。

4.union、union all:union在链接表后会去掉重复的记录,多了一步去重操作;union all只简单链接表将结果集返回,不会去重,推荐。

5.order by、group by:排序、分组,要使用索引字段,否则效率低。

6.is null、is not null:因为索引不会索引空值,所以会造成非索引查询,效率低。

7.>=、<=:用于索引字段会采取索引,非索引字段会全表扫描查询。

8.or:慎用,即使用了也要结合索引字段查询。

9.count(1):统计查询用 select count(1) from [table A],因为count(1)的效率远大于count(*)

三、sql

1.sql执行顺序:先子查询,后外部查询,因此子查询应精确查询,尽可能缩小子查询结果集。

2.存储过程:

3.试图:多表连接查询

4.批量插入数据,应尽可能一次执行,而非一次一次执行。

四、示例

eg1:union all 代替 or

1 select id,status,extendProxy from A where status = 2 or extendProxy =10032 select id,status,extendProxy from A where status = 2
3 union all
4 select id,status,extendProxy from A where extendProxy  =1003
View Code

 

posted @ 2023-04-12 10:58  小黄鸭  阅读(53)  评论(2)    收藏  举报