Monday, July 18, 2011

Why is my SQL query taking forever to run?

All of us must have been in this situation before.
Why is SQL taking forever to run today? Until today, it was taking minutes and today it is running forever.

This is the worst nightmare for a DBA. In this situation, the most likely scenario is that SQL is running with a different execution plan as opposed to when it was taking minutes.
How do we find it out?
The below SQL will give you all the child cursor for the SQL in question. Just pass the SQL id of the problem SQL. If you see multiple PLAN_HASH_VALUE for this given SQL, that means this SQL indeed has multiple execution plans. One of them being the efficient one that it had been using. 

select
inst_id,sql_id,plan_hash_value,child_number,executions,round(buffer_gets/executions,2)
"buffer_gets/exec" , cpu_time/1000000 "Cpu Time(s)",round(rows_processed/executions,2) "Rows",
elapsed_time/1000000 "Elpased Time(s)"  from gv$sql where
sql_id='&sql_id'
 
Once we know all the child cursors, run the below SQL to get the execution plan for all the child cursor and see why it is taking forever for this run.

select * from TABLE(dbms_xplan.display_cursor('&SQL_ID',&child_cursor,'PEEKED_BINDS'))

Just Pass the SQL id and the child cursor and you will be able to the execution plan.

No comments:

Post a Comment