Question: How do I query to find
long-running queries? I want to identify SQL queries
that are running for an inordinate amount of time.
Answer: You can query the
v$session_longops view to find long-running queries and
you can query the AWR to find historical queries (if you
have purchased the AWR packs)..
The Oracle
data dictionary contains a little-known view called the
v$session_longops. The
v$session_longops
view allows the Oracle professional contract the amount of time
that is used by long-running DLL and DML statements.
You can view
any SQL statement that executes for more than 6 absolute seconds
(the "long running" threshold) using the v$session_longops view.
Here are some example scripts to find
long running queries:
select * from
(
select
opname,
start_time,
target,
sofar,
totalwork,
units,
elapsed_seconds,
message
from
v$session_longops
order by start_time desc
)
where rownum <=1;
This query for long running SQL
is especially useful when
operations contain long running loops such as shown in the
example below.
DECLARE
l_rindex PLS_INTEGER;
l_slno PLS_INTEGER;
l_totalwork NUMBER;
l_sofar NUMBER;
l_obj PLS_INTEGER;
BEGIN
l_rindex := DBMS_APPLICATION_INFO.set_session_longops_nohint;
l_sofar := 0;
l_totalwork := 10;
WHILE l_sofar < 10 LOOP
-- Do some work
DBMS_LOCK.sleep(5);
l_sofar := l_sofar + 1;
DBMS_APPLICATION_INFO.set_session_longops(
rindex => l_rindex,
slno => l_slno,
op_name => 'BATCH_LOAD',
target => l_obj,
context => 0,
sofar => l_sofar,
totalwork => l_totalwork,
target_desc => 'BATCH_LOAD_TABLE',
units => 'rows');
SEE CODE DEPOT FOR FULL SCRIPT
END LOOP;
END;
/
While
the above code is running, the contents of the
v$session_longops view can be queried as follows.
COLUMN
opname FORMAT A20
COLUMN target_desc FORMAT A20
COLUMN
units FORMAT A10
select
opname,
target_desc,
sofar,
totalwork,
time_remaining,
units
from
v$session_longops
SEE CODE DEPOT FOR FULL SCRIPT
The
type of output expected from this v$session_longops
query is listed below.
OPNAME
TARGET_DESC
SOFAR TOTALWORK UNITS
-------------------- -------------------- ----------
---------- ----
BATCH_LOAD BATCH_LOAD_TABLE
3 10
rows
Querying AWR for historical long running SQL
Here is a SQL query to locate historical SQL (over the past 40 days) that has an execution time greater than 20 wall clock seconds: