Tune slow running query
Reading time: 3 - 4 minutes
Today happed had a situation where i were called by my client and informed about slow generation of report.
Client was using some SQL which was selecting some data from few tables to generate reports.
I used the following query to find out how much it used to take in past.
set lines 155
col execs for 999,999,999
col avg_etime for 999,999.999
col avg_lio for 999,999,999.9
col begin_interval_time for a30
col node for 99999
break on plan_hash_value on startup_time skip 1
select ss.snap_id, ss.instance_number node, begin_interval_time, sql_id, plan_hash_value,
nvl(executions_delta,0) execs,
(elapsed_time_delta/decode(nvl(executions_delta,0),0,1,executions_delta))/1000000 avg_etime,
(buffer_gets_delta/decode(nvl(buffer_gets_delta,0),0,1,executions_delta)) avg_lio
from DBA_HIST_SQLSTAT S, DBA_HIST_SNAPSHOT SS
where sql_id = nvl('&sql_id','4dqs2k5tynk61')
and ss.snap_id = S.snap_id
and ss.instance_number = S.instance_number
and executions_delta > 0
order by 1, 2, 3
/
As per the output i can see that SQL has changed the execution plan from 2PM on 29th JUL 10.
As per the Oracle documentation , i decided to use SQL Tuning Advisor
SQL Tuning Advisor has three steps.
- Create Tuning Task ( DBMS_SQLTUNE.CREATE_TUNING_TASK )
- Execute Tuning Task ( DBMS_SQLTUNE.EXECUTE_TUNING_TASK )
- Report Tuning Task ( DBMS_SQLTUNE.REPORT_TUNING_TASK )
I created SQL Tuning task using following script.
SET LONG 10000;
SET PAGESIZE 9999
SET LINESIZE 155
set verify off
col recommendations for a150
accept task_name -
prompt 'Task_Name: '
DECLARE
ret_val VARCHAR2(4000);BEGIN
ret_val := dbms_sqltune.create_tuning_task(task_name=>'&&Task_name', sql_id=>'&sql_id', time_limit=>&time_limit);
dbms_sqltune.execute_tuning_task('&&Task_name');
END;
/
SELECT DBMS_SQLTUNE.report_tuning_task('&&task_name') AS recommendations FROM dual;
undef task_name
Tuning Advisor's Primary recommendations are often to accept a SQL Profile but there may be other recommendations such as creating indexes, etc.
As per my past experience never ever accept recommendation blindly else you may be in problem.
SQL tuning advisor suggested SQL profile and i accepted it and it improved performance dramatically.
Script Source:
http://kerryosborne.oracle-guy.com/2008/09/sql-tuning-advisor/