/*
 * Title  : awr_uns_plan.sql
 * Author : EXADIME LLC
 * Created: 29-Jul-2017
 * Updated: 07-Dec-2018
 * Release: 1.0.0
 * Purpose: To show unstable plans.
 * History: N/A
 */

start oracle.ini

set echo off
set feedback off
set serverout on
set termout on

set linesize 125
set pagesize 0
set pause off
set long 80

set heading on
set headsep on
set underline on
set colsep " "

set define on
set verify off
set escape off
set embedded on

column sno			format 999		heading "#"
column snid			format 999999		heading "Snap Id"
column time			format a15		heading "Snap Time"
column sql_id			format a15		heading "SQL Id"
column tot_execs		format 999,999,999	heading "Executions"
column min_etime		format 999,999.99	heading "Min Elapsed Time"
column max_etime		format 999,999.99	heading "Max Elapsed Time"
column norm_stddev		format 999,999.9999	heading "Deviation"

accept p_bsnap	prompt "Enter Begin Snap Id: "
accept p_esnap	prompt "Enter End Snap Id: "
accept p_min_stddev char prompt "Enter minimum deviation (Default 2X): "
accept p_min_etime char prompt "Enter minimum elapsed time (Default 0.1 Sec): "
accept p_order	prompt "Enter sort order [asc|desc]: "

spool &&rpt_dir/awr_uns_plan.rpt

select
	row_number() over(order by snap_id &&p_order)		sno,
	snap_id							snid,
	to_char(snap_time,'yyyymmdd hh24:mi')			time,
	sql_id,
	tot_execs,
	min_etime,
	max_etime,
	norm_stddev
from (
	select 
		snap_id,
		snap_time,
		sql_id				sql_id,
		sum(execs)			tot_execs,
		min(avg_etime)			min_etime,
		max(avg_etime)			max_etime,
		stddev_etime/min(avg_etime)	norm_stddev 
	from (
		select 
			snap_id,
			snap_time,
			sql_id,
			plan_hash_value,
			execs,
			avg_etime,
			stddev(avg_etime) over (partition by sql_id) stddev_etime
		from (
			select 
				ss.snap_id,
				ss.begin_interval_time snap_time,
				sql_id,
				plan_hash_value,
				sum(nvl(executions_delta,0)) execs,
				(sum(elapsed_time_delta)/decode(sum(nvl(executions_delta,0)),0,1,sum(executions_delta))/1000000) avg_etime,
				sum((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 
				ss.snap_id = s.snap_id
			and	ss.instance_number = s.instance_number
			and	executions_delta > 0
			and	s.snap_id between &p_bsnap and &p_esnap
			group by 
				ss.snap_id,
				ss.begin_interval_time,
				sql_id, 
				plan_hash_value
		)
	)
	group by 
		snap_id,
		snap_time,
		sql_id, 
		stddev_etime
)
where 
	norm_stddev > nvl(to_number('&p_min_stddev'),2)
	and min_etime > nvl(to_number('&p_min_etime'),0.1);

spool off

clear columns

set embedded off
set escape off
set verify on
set define on

set colsep " "
set underline on
set headsep on
set heading on

set pause off
set pagesize 24
set linesize 80
set long 80

set termout on
set serverout off
set feedback on
set echo off
