24. 用explain plan 分析sql语句
explain plan 是一个很好的分析sql语句的工具,它甚至可以在不执行sql的情况下分析语句. 通过分析,我们就可以知道oracle是怎么样连接表,使用什么方式扫描表(索引扫描或全表扫描)以及使用到的索引名称.
你需要按照从里到外,从上到下的次序解读分析的结果. explain plan分析的结果是用缩进的格式排列的, 最内部的操作将被最先解读, 如果两个操作处于同一层中,带有最小操作号的将被首先执行.
nested loop是少数不按照上述规则处理的操作, 正确的执行路径是检查对nested loop提供数据的操作,其中操作号最小的将被最先处理.
译者按:
通过实践, 感到还是用sqlplus中的set trace 功能比较方便.
举例:
sql> list
1 select *
2 from dept, emp
3* where emp.deptno = dept.deptno
sql> set autotrace traceonly /*traceonly 可以不显示执行结果*/
sql> /
14 rows selected.
execution plan
----------------------------------------------------------
0 select statement optimizer=choose
1 0 nested loops
2 1 table access (full) of 'emp'
3 1 table access (by index rowid) of 'dept'
4 3 index (unique scan) of 'pk_dept' (unique)
statistics
----------------------------------------------------------
0 recursive calls
2 db block gets
30 consistent gets
0 physical reads
0 redo size
2598 bytes sent via sql.net to client
503 bytes received via sql.net from client
2 sql.net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
14 rows processed
通过以上分析,可以得出实际的执行步骤是:
1. table access (full) of 'emp'
2. index (unique scan) of 'pk_dept' (unique)
3. table access (by index rowid) of 'dept'
4. nested loops (joining 1 and 3)
注: 目前许多第三方的工具如toad和oracle本身提供的工具如oms的sql analyze都提供了极其方便的explain plan工具.也许喜欢图形化界面的朋友们可以选用它们.
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器