/*
 * Title  : awr_plan_hist.sql
 * Author : EXADIME LLC
 * Created: 29-Jul-2017
 * Updated: 01-Nov-2023
 * Release: 1.0.0
 * Purpose: To show AWR plan changes for SQL Id.
 * History: Order by snap.
 */

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 node	format 999,999		heading "Node"
column time	format a15		heading "Snap Time"
column sqid	format a15		heading "SQL Id"
column hash	format 999999999999	heading "Plan Hash Value"
column exec	format 999,999,999	heading "Executions"
column avgt	format 999,999,999	heading "Seconds|Avg Elapsed Time"
column alio	format 999,999,999,9	heading "Avg Logical I/O"

break on plan_hash_value on startup_time skip 1

accept p_bsnap	prompt "Enter Begin Snap Id: "
accept p_esnap	prompt "Enter End Snap Id: "
accept p_sqlid  char prompt "Enter SQL Id: "
accept p_order  char prompt "Enter order by column {1|2|3|4|5|6|7|8|9} [asc|desc]: " default 2

spool &&rpt_dir/awr_plan_hist.rpt

select 
	row_number() over(order by &&p_order)							sno,
	snap_id											snid,
	instance_number										node,
	to_char(begin_interval_time,'yyyymmdd hh24:mi')						time,
	sql_id											sqid,
	plan_hash_value										hash,
	nvl(executions_delta,0)									exec,
	(elapsed_time_delta/decode(nvl(executions_delta,0),0,1,executions_delta))/1000000	avgt,
	(buffer_gets_delta/decode(nvl(buffer_gets_delta,0),0,1,executions_delta))		alio
from (
	select 
		ss.snap_id,
		ss.instance_number,
		begin_interval_time,
		sql_id,
		plan_hash_value,
		executions_delta,
		elapsed_time_delta,
		buffer_gets_delta
	from
		dba_hist_sqlstat s,
		dba_hist_snapshot ss
	where 
		sql_id = '&p_sqlid'
		and 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
) order by
	&&p_order
/

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
