SQL优化常见面试注意点
现在面试过程中,除了开发的基础,面试官通常还会问SQL优化的方面,SQL优化也能体现出来平时对数据库的理解和技术的高低。现在就总结了几个,希望对大家有帮助。好记性不如烂笔头,在此记录,方便以后查阅。有不足之处请大家指出!
1. 索引
在表中建立索引,优先考虑where、group by使用到的字段。
2. Where查询
查询条件中,一定不要使用select * ,* 因为会返回过多无用的字段会降低查询效率。应该使用具体的字段代替 *,只返回使用到的字段。
3. 模糊查询
不要在where条件中使用左右两边都是%的like模糊查询,如:
select * from t_order where customer like ‘%zhang%’;
这样会导致数据库引擎放弃索引进行全表扫描;尽量在字段后面使用模糊查询。如下:
select * from t_order where customer like ‘zhang%’;
4. in和not in
尽量不要使用in 和not in,会造成全表扫描。如下:
select * from t_order where id in (2,3);
select * from t_order1 where customer in (select customer from t_order2);
对于连续的数值,能用 between 就不要用 in ,如下:
select * from t_order where id between 2 and 3;
对于子查询,可以用exists代替。如下:
select * from t_order1 where exists (select * from t_order2 where
t1.customer = t2.customer);
5.关于or
尽量不要使用or,会造成全表扫描。如下:
select * from t_order where id = 1 or id = 3;
可以用union代替or。如下:
select * from t_order where id = 1 union select * from t_order
where id = 3;
6.where子句中的表达式
尽量不要在 where 子句中对字段进行表达式操作,这样也会造成全表扫描。如下:
select id from t_order where num/2=100;
应改为:
select id from t_order where num=100*2;
7.where子句中的null值判断
where条件里尽量不要进行null值的判断,null的判断也会造成全表扫描。如下:
selecct * from t_order where score is null;
优化如下:
给字段添加默认值,对默认值进行判断。
如:select * from t_order where score = 0;
8.where条件左侧表达式
尽量不要在where条件中等号的左侧进行表达式.函数操作,会导致全 表扫描。如下:
select * from t_order2 where score/10 = 10 select * from t_order2 where substr(customer,1,5) = ‘zhang’;
将表达式.函数操作移动到等号右侧。优化如下:
select * from t_order2 where score = 10*10 select * from t_order2 where customer like ‘zhang%’;
9.where 1=1的条件
尽量不要使用where 1=1的条件 有时候,在开发过程中,为了方便拼装查询条件,我们会加上该条件,这样,会造成进行全表扫描; 如下:
SELECT * FROM t_order WHERE 1=1
优化如下:
如果用代码拼装sql,则由代码进行判断,没where加where,有where加and;如果用mybatis,请用mybatis的where语法。
10.注意事项
程序要尽量避免大事务操作,提高系统并发能力。
一个表的索引数最好不要超过6个,如果索引太多的话,就需要考虑一下那些不常使用到的列上建的索引是否有必要。