Tuesday, August 3, 2021

How to Determine the SQL_ID for a SQL Statement

 How to Determine the SQL_ID for a SQL Statement 


How to determine the SQL_ID for a SQL Statement's associated text using Data Dictionary queries that execute against the V$SQL view, AWR & ASH data or associated views.


How to identify the SQL_ID of a statement

The SQL_ID of a statement can be found in an AWR or ASH report or by selecting it from the database data dictionary using the V$SQL view.

If the SQL can be identified with a particular identifiable string or by some kind of unique comment such as: /* TARGET SQL */ then this will make it easier to locate.


For Example:


SELECT /* TARGET SQL */ * FROM dual;

SELECT sql_id, plan_hash_value, substr(sql_text,1,40) sql_text  
FROM  v$sql 
WHERE sql_text like 'SELECT /* TARGET SQL */%'

SQL_ID        PLAN_HASH_VALUE SQL_TEXT
------------- --------------- ----------------------------------------
0xzhrtn5gkpjs       272002086 SELECT /* TARGET SQL */ * FROM dual

The plan_hash_value is included here for convenience.

You can also find the SQL_ID in the V$SQL view using a substitution variable:


SELECT sql_id, plan_hash_value, SUBSTR(sql_text,1,40) Text
FROM v$sql
WHERE sql_text LIKE '%&An_Identifiable_String%';

If SQL is no longer available in v$sql, you can find it in the 
AWR history views: DBA_HIST_SQLTEXT and DBA_HIST_SQLSTAT :
SELECT
    s.sql_id,
    s.plan_hash_value,
    t.sql_text,
    s.snap_id
FROM
    dba_hist_sqlstat   s,
    dba_hist_sqltext   t
WHERE s.dbid = t.dbid
AND   s.sql_id = t.sql_id
AND   sql_text LIKE 'SELECT /* TARGET SQL */%'
ORDER BY
    s.sql_id

You can use the snap_id to determine when the SQL was executed along with 
other information from AWR.

No comments: