20. 用表连接替换exists
通常来说 , 采用表连接的方式比exists更有效率
select ename
from emp e
where exists (select ‘x’
from dept
where dept_no = e.dept_no
and dept_cat = ‘a’);
(更高效)
select ename
from dept d,emp e
where e.dept_no = d.dept_no
and dept_cat = ‘a’ ;
(译者按: 在rbo的情况下,前者的执行路径包括filter,后者使用nested loop)
21. 用exists替换distinct
当提交一个包含一对多表信息(比如部门表和雇员表)的查询时,避免在select子句中使用distinct. 一般可以考虑用exist替换
例如:
低效:
select distinct dept_no,dept_name
from dept d,emp e
where d.dept_no = e.dept_no
高效:
select dept_no,dept_name
from dept d
where exists ( select ‘x’
from emp e
where e.dept_no = d.dept_no);
exists 使查询更为迅速,因为rdbms核心模块将在子查询的条件一旦满足后,立刻返回结果.
22. 识别’低效执行’的sql语句
用下列sql工具找出低效sql:
select executions , disk_reads, buffer_gets,
round((buffer_gets-disk_reads)/buffer_gets,2) hit_radio,
round(disk_reads/executions,2) reads_per_run,
sql_text
from v$sqlarea
where executions>0
and buffer_gets > 0
and (buffer_gets-disk_reads)/buffer_gets < 0.8
order by 4 desc;
(译者按: 虽然目前各种关于sql优化的图形化工具层出不穷,但是写出自己的sql工具来解决问题始终是一个最好的方法)
23. 使用tkprof 工具来查询sql性能状态
sql trace 工具收集正在执行的sql的性能状态数据并记录到一个跟踪文件中. 这个跟踪文件提供了许多有用的信息,例如解析次数.执行次数,cpu使用时间等.这些数据将可以用来优化你的系统.
设置sql trace在会话级别: 有效
alter session set sql_trace true
设置sql trace 在整个数据库有效仿, 你必须将sql_trace参数在init.ora中设为true, user_dump_dest参数说明了生成跟踪文件的目录
(译者按: 这一节中,作者并没有提到tkprof的用法, 对sql trace的用法也不够准确, 设置sql trace首先要在init.ora中设定timed_statistics, 这样才能得到那些重要的时间状态. 生成的trace文件是不可读的,所以要用tkprof工具对其进行转换,tkprof有许多执行参数. 大家可以参考oracle手册来了解具体的配置. )