標籤:
前言
一個系統在剛開始的時候,由於資料庫中資料量不大,開發人員的主要精力都在業務與功能實現上。系統完成部署上線後隨著時間的累積,每個表中的資料都在不斷增長,我們往往會發現系統越來越慢,這可能是程式設計不合理,也可能是代碼品質不高,也可能是商務程序問題,但是作為DBA或者負責資料庫調優的工程師更應該想想是否是資料庫方面的問題。資料庫問題有很多種,作為開發人員主要關注SQL語句的合理性,至於資料庫的其它問題可以暫時交給DBA去處理。對SQL語句調優,很重要的一點是查看SQL語句的執行計畫。本文將簡單介紹如何查看Oracle資料庫中的執行計畫。
執行計畫的清除
Oracle資料庫的執行計畫實際都儲存在plan_table這張表中,也許已經有人做過查看執行計畫的工作,那麼plan_table中必然存在很多曆史的執行計畫。為了不影響之後的工作,最好能將之前的執行計畫都刪除。
首先,我們先以sysdba帳號通過sqlplus串連Oracle:
[[email protected] ~]$ sqlplus / as sysdbaSQL*Plus: Release 10.2.0.5.0 - Production on Mon May 19 15:56:14 2014Copyright (c) 1982, 2010, Oracle. All Rights Reserved.Connected to:Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bit ProductionWith the Partitioning, OLAP, Data Mining and Real Application Testing options
然後刪除plan_table這張表:
SQL> drop table plan_table;Table dropped.
最後退出sqlplus:
SQL> drop table plan_table;Table dropped.
重新開啟執行計畫
我們再次以sysdba帳號通過sqlplus串連Oracle,開啟執行計畫的步驟如下:
1、重新建立收集執行計畫的表plan_table;
SQL> @?/rdbms/admin/utlxplan.sql;Table created.
2、建立plan_table這張表的別名,因為同義字可以節省大量的資料庫空間,不同使用者操作同一張表時不會有多少差別。
SQL> create public synonym plan_table for plan_table;Synonym created.
3、給我們自己的帳號myaccount授予plan_table表的所有許可權;
SQL> grant all on plan_table to myaccount;Grant succeeded.
4、建立plustrace角色;
SQL> @?/sqlplus/admin/plustrce.sqlSQL> create role plustrace;Role created.
5、將給角色添加訪問以下視圖的許可權;
SQL> grant select on v_$sesstat to plustrace;Grant succeeded.SQL> grant select on v_$statname to plustrace;Grant succeeded.SQL> grant select on v_$mystat to plustrace;Grant succeeded.SQL> grant plustrace to dba with admin option;Grant succeeded.
6、設定不把輸出的結果顯示在螢幕上;
SQL> set echo off
7、將plustrace角色授權給帳號myaccount;
SQL> grant plustrace to myaccount;Grant succeeded.
8、使用帳號myaccount串連Oracle;
SQL> conn myaccount/myaccount;Connected.
9、設定只查看執行計畫的統計資訊;
set autotrace traceonly statistics;
應用舉例
我們以下面的SQL為例,來查看其執行計畫:
SQL> select * from t_recharge_info where recharge_sid=‘14051317413765487300000002‘;Statistics---------------------------------------------------------- 0 recursive calls 0 db block gets 23 consistent gets 0 physical reads 0 redo size 2093 bytes sent via SQL*Net to client 492 bytes received via SQL*Net from client 2 SQL*Net roundtrips to/from client 0 sorts (memory) 0 sorts (disk) 1 rows processed
從上面的SQL例子,我們看到輸出了這條SQL的執行計畫的統計資訊,要設定查看執行計畫,可以執行以下命令:
SQL> set autotrace on explain;
總結
從Oracle執行計畫的配置我們瞭解到,只需要跟著這些步驟就可以查看SQL的執行計畫及統計資訊。這些內容比較簡單,沒有什麼深奧的原理,寫此博文是為了方便記憶,為將來做個備忘。
Oracle執行計畫的查看