一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第21天,点击查看活动详情。
收集整理的常用sql优化
1.建立索引
对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。
2.尽量避免!=或<>操作符
应尽量避免在 where 子句中使用!=或<>操作符,否则将引擎放弃使用索引而进行全表扫描。
3.尽量避免对null判断
应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:
select id from t where code is null
可以在num上设置默认值0,确保表中num列没有null值,然后这样查询:
select id from t where code=0
4.尽量避免使用or
应尽量避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,如:
select id from t where code=10 or code=20
可以这样查询:
select id from twhere code=10 union all select id from t where code=20
5.in 和 not in 慎用
in 和 not in 也要慎用,否则会导致全表扫描,如:
select id from t where code in(1,2,3)
对于连续的数值,能用 between 就不要用 in 了:
select id from t where code between 1 and 3
6.exists 代替 in
很多时候用 exists 代替 in 是一个好的选择:
select code from a where code in(select code from b)
用下面的语句替换:
select code from a where exists (select 1 from b where code=a.code)
7.索引并不是越多越好
索引并不是越多越好,索引固然可以提高相应的 select 的效率,但同时也降低了 insert 及 update 的效率,因为 insert 或 update 时有可能会重建索引,所以怎样建索引需要慎重考虑,视具体情况而定。一个表的索引数最好不要超过6个,若太多则应考虑一些不常使用到的列上建的索引是否有必要。
8.数值信息的字段尽量使用数字型字段
尽量使用数字型字段,若只含数值信息的字段尽量不要设计为字符型,这会降低查询和连接的性能,并会增加存储开销。这是因为引擎在处理查询和连接时会逐个比较字符串中每一个字符,而对于数字型而言只需要比较一次就够了。
9.尽可能的使用 varchar/nvarchar 代替 char/nchar
尽可能的使用 varchar/nvarchar 代替 char/nchar ,因为首先变长字段存储空间小,可以节省存储空间,其次对于查询来说,在一个相对较小的字段内搜索效率显然要高些。
9.不要使用 select * from t
任何地方都不要使用 select * from t ,用具体的字段列表代替“*”,不要返回用不到的任何字段。