Skip to content
pvmehta.com

pvmehta.com

  • Home
  • About Me
  • Toggle search form
  • mutex in Oracle 10.2.0.2 or Oracle 10g Oracle
  • Linux CPU info. Linux/Unix
  • Python class import from different folders Python/PySpark
  • How to connect to Oracle Database with Wallet with Python. Oracle
  • fuser to check who is using diretory Linux/Unix
  • Search and replace editor command in vi Linux/Unix
  • cold backup scripts to copy locally Linux/Unix
  • Sample WW22 listener.ora Oracle
  • crontab syntax Linux/Unix
  • Rman Notes -1 Oracle
  • Remove DOS CR/LFs (^M) Linux/Unix
  • plan10g.sql good Oracle
  • metalink all dynamic view reference notes. Oracle
  • proper cpu stats Linux/Unix
  • V$transaction notes for finding XID composition. Oracle

tracksqltime.sql

Posted on 05-Mar-2026 By Admin No Comments on tracksqltime.sql

This PL/SQL block identifies recently active SQL queries from a specific application server and provides details on their performance and execution plans. 

Here is a breakdown of what the script does:

  • Filters Activity: It scans the Active Session History (gv$active_session_history) to find distinct SQL IDs triggered by machines containing “APP02” in their name within the last hour.
  • Retrieves SQL Text: For each identified SQL ID, it attempts to fetch the actual SQL statement from the library cache (gv$sql). If the text is no longer in memory, it labels it as “NO SQL TEXT.”
  • Analyzes Execution Plans: It looks for all unique Plan Hash Values associated with that SQL ID, searching both real-time memory (gv$sql_plan) and historical records (dba_hist_sql_plan).
  • Calculates Performance: For every execution plan found, it calculates the Average Elapsed Time (in seconds) by checking current statistics and historical snapshots (dba_hist_sqlstat).
  • Displays Results: It prints a formatted report to the console showing the SQL ID, the machine name, the SQL text, and a list of all known execution plans with their respective average timings. 
set lines 120 pages 200;
SET SERVEROUTPUT ON;

DECLARE
  header  varchar2(300);
  tmp_sqltext  varchar2(1000);
  CURSOR c1 IS
    SELECT distinct  SQL_ID, machine, program
    FROM gv$active_session_history
    WHERE upper(machine) LIKE upper('%XAAPP02%')
      AND sample_time > SYSDATE - 1/24
      AND sql_id IS NOT NULL ;
BEGIN
--  header := lpad('SQL_ID', 15) || lpad('PHV', 15) || lpad('Avg ET', 14) || lpad('Machine', 30);
--  DBMS_OUTPUT.PUT_LINE(header);
  FOR cur1 IN c1 LOOP
    begin
    select sql_text into tmp_sqltext from gv$sql where sql_id = cur1.sql_id and rownum = 1;
    exception
       when no_data_found then
            tmp_sqltext := 'NO SQL TEXT in V$SQL';
    end;
    dbms_output.put_line(lpad('------------------', 25));
    DBMS_OUTPUT.PUT_LINE(lpad(cur1.sql_id,15) || lpad(cur1.machine, 30) || ' ' || chr(10) || tmp_sqltext);
    begin
    -- Nested loop to handle 1-to-many relationship between SQL_ID and Plans
    FOR plan_cur IN (
        WITH
        p AS (
            SELECT plan_hash_value FROM gv$sql_plan
             WHERE sql_id = cur1.sql_id AND other_xml IS NOT NULL
             UNION
            SELECT plan_hash_value FROM dba_hist_sql_plan
             WHERE sql_id = cur1.sql_id AND other_xml IS NOT NULL
        ),
        m AS (
            SELECT plan_hash_value,
                   SUM(elapsed_time)/SUM(executions) avg_et_secs
              FROM gv$sql
             WHERE sql_id = cur1.sql_id AND executions > 0
             GROUP BY plan_hash_value
        ),
        a AS (
            SELECT plan_hash_value,
                   SUM(elapsed_time_total)/SUM(executions_total) avg_et_secs
              FROM dba_hist_sqlstat
             WHERE sql_id = cur1.sql_id AND executions_total > 0
             GROUP BY plan_hash_value
        )
        SELECT p.plan_hash_value,
               ROUND(NVL(m.avg_et_secs, a.avg_et_secs)/1e6, 3) AS avg_et_secs
          FROM p
          LEFT JOIN m ON p.plan_hash_value = m.plan_hash_value
          LEFT JOIN a ON p.plan_hash_value = a.plan_hash_value
    ) LOOP
      -- This prints for every plan found for the current SQL_ID
      DBMS_OUTPUT.PUT_LINE( lpad(plan_cur.plan_hash_value,15) || ' ' || lpad(plan_cur.avg_et_secs,10));
    END LOOP;
    exception
        when no_data_found  then
             DBMS_OUTPUT.PUT_LINE( 'NO PLAN INFO AVAILABLE');

    end;
  END LOOP;
END;
/
Oracle, SQL scripts

Post navigation

Previous Post: Complete Git Tutorial for Beginners

Related Posts

  • ORACLE_SID in sqlplus Oracle
  • My Test Case On 21-OCT-2005 Oracle
  • Multiple listeners Oracle
  • Adding or Dropping Online Redo Log Files When Physical Standby in place Oracle
  • sql_plan9i.sql Oracle
  • Temporary Tablespsace Temp tablespace behaviour Oracle

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Ansible (0)
  • AWS (2)
  • Azure (1)
  • Django (0)
  • GIT (1)
  • Linux/Unix (149)
  • MYSQL (5)
  • Oracle (394)
  • PHP/MYSQL/Wordpress (10)
  • POSTGRESQL (1)
  • Power-BI (0)
  • Python/PySpark (7)
  • RAC (17)
  • rman-dataguard (26)
  • shell (149)
  • SQL scripts (343)
  • SQL Server (6)
  • Uncategorized (0)
  • Videos (0)

Recent Posts

  • tracksqltime.sql05-Mar-2026
  • Complete Git Tutorial for Beginners25-Dec-2025
  • Postgres DB user and OS user.25-Dec-2025
  • Trace a SQL session from another session using ORADEBUG30-Sep-2025
  • SQL Server Vs Oracle Architecture difference25-Jul-2025
  • SQL Server: How to see historical transactions25-Jul-2025
  • SQL Server: How to see current transactions or requests25-Jul-2025
  • T-SQL Vs PL/SQL Syntax25-Jul-2025
  • Check SQL Server edition25-Jul-2025
  • Checking SQL Server Version25-Jul-2025

Archives

  • 2026
  • 2025
  • 2024
  • 2023
  • 2010
  • 2009
  • 2008
  • 2007
  • 2006
  • 2005
  • purge_trc.sh Linux/Unix
  • Best approach for Oracle database patching sequence to latest/required patchset along with CPU/PSU/any-other-one-off patch ID 865255.1 Oracle
  • Create type and Grant on it. Oracle
  • Optimizer SORT Operations Oracle
  • Looping for remote servers and find its database from oratab file. Linux/Unix
  • Running some SQL on multiple databases connecting using monitoring userid and password Linux/Unix
  • cache buffer chain latch Oracle
  • Index Range Scan Oracle

Copyright © 2026 pvmehta.com.

Powered by PressBook News WordPress theme