常用的7个SQl优化技巧
作为程序员经常和数据库打交道的时候还是非常频繁的,掌握住一些Sql的优化技巧还是非常有必要的。下面列出一些常用的SQl优化技巧,感兴趣的朋友可以了解一下。
1、注意通配符中Like的使用
以下写法会造成全表的扫描,例如:
select id,name from userinfo where name like '%name%' 或者 select id,name from userinfo where name like '%name'
下面的写法执行效率快很多,因为它使用了索引
select id,name from userinfo where name like 'name%'
2、避免在where子句中对字段进行函数操作
比如:
select id from userinfo where substring(name,1,6) = 'xiaomi' 或者 select id from userinfo where datediff(day,datefield,'2017-05-17') >= 0
上面两句都对字段进行了函数处理,会导致查询分析器放弃了索引的使用。
正确的写法:
select id from userinfo where name like'xiaomi%' select id from userinfo where datefield <= '2017-05-17'
通俗理解就是where子句‘=’ 左边不要出现函数、算数运算或者其他表达式运算
3、在子查询当中,尽量用exists代替in
select name from userinfo a where id in(select id from userinfo b) 可以改为 select name from userinfo a where exists(select 1 from userinfo b where id = a.id)
下面的查询速度比in查询的要快很多。
4、where子句中尽量不要使用is null 或 is not null对字段进行判断
例如:
select id from userinfo where name is null
尽量在数据库字段中不出现null,如果查询的时候条件为 is null ,索引将不会被使用,造成查询效率低,
因此数据库在设计的时候,尽可能将某个字段可能为空的时候设置默认值,那么查询的时候可以
根据默认值进行查询,比如name字段设置为0,查询语句可以修改为
select id from userinfo where name=0
5、避免在where子句使用or作为链接条件
例如:
select id from userinfo where name='xiaoming' or name='xiaowang' 可以改写为: select id from userinfo where name = 'xiaoming' union all select id from userinfo where name = 'xiaowang'
6、避免在 where 子句中使用 != 或 <> 操作符。
例如:
select name from userinfo where id <> 0
说明:数据库在查询时,对 != 或 <> 操作符不会使用索引,
而对于 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,数据库才会使用索引。
因此对于上面的查询,正确写法可以改为:
select name from userinfo where id < 0 union all select name from userinfo where id > 0
7、少用in 或 not in
对于连续的数值范围查询尽量使用BETWEEN AND,例如:
select name from userinfo where id BETWEEN 10 AND 70
以上只是相对来说比较常用的sql优化技巧,当然还有很多欢迎补充!
欢迎关注公众号:DoNet技术分享平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2016-06-17 微信热传的 100+ 经典技术文章(转)