简单的sql查询优化
2015-06-04 15:40
281 查看
1、sql中禁止用select * from 的写法 (缺点:将会增加服务区IO的输出负担)
2、如果一个sql比较复杂 则写完的sql 可以用 在plsql 中用f5 来看起执行计划,
例如sql
select * from exp_booking
where booking_id like
'%1231231231%'
在执行计划中如果看到 table accessfull 这种标记务必注意,此标记代表全表访问,如果您的表有上百万数据,那么其将会对数据库造成非常大的IO读取瓶颈,则需要对其sql进行优化,使其走索引,例如
select * from exp_booking
where booking_id =
'1231231231'
此种状态代表执行sql 走了相应的索引,则我们可以看到后面的cost 为2,其消耗cup的性能比较小
3、禁止写破坏索引的sql语句,以下情况为不能使用索引的写法
(1)在where条件中使用函数
如:where substr(…… 字段为字符型的查询whereinstate=’5’ ;instate=5 会用to_number
(2)>;not in;LIKE %_开头不走索引 。 >=BETWEEN,IN,LIKE不以%_开头使用索引
(3)建立的索引字段中,不能有空值
(4)or 不走索引 查询是可以用 selectid from ….. union all select if from ……
(5)不要用 wm_contact
(6)按id插入多条记录时不要用循环,
要用 Insert intoTable2(field1,field2,...) select value1,value2,... from Table1
2、如果一个sql比较复杂 则写完的sql 可以用 在plsql 中用f5 来看起执行计划,
例如sql
select * from exp_booking
where booking_id like
'%1231231231%'
在执行计划中如果看到 table accessfull 这种标记务必注意,此标记代表全表访问,如果您的表有上百万数据,那么其将会对数据库造成非常大的IO读取瓶颈,则需要对其sql进行优化,使其走索引,例如
select * from exp_booking
where booking_id =
'1231231231'
此种状态代表执行sql 走了相应的索引,则我们可以看到后面的cost 为2,其消耗cup的性能比较小
3、禁止写破坏索引的sql语句,以下情况为不能使用索引的写法
(1)在where条件中使用函数
如:where substr(…… 字段为字符型的查询whereinstate=’5’ ;instate=5 会用to_number
(2)>;not in;LIKE %_开头不走索引 。 >=BETWEEN,IN,LIKE不以%_开头使用索引
(3)建立的索引字段中,不能有空值
(4)or 不走索引 查询是可以用 selectid from ….. union all select if from ……
(5)不要用 wm_contact
(6)按id插入多条记录时不要用循环,
要用 Insert intoTable2(field1,field2,...) select value1,value2,... from Table1