How to force a execution plan

Hello ,
I am working on oracle 11g R2 on AIX.
One query was performing good around 20 sec. but suddenly it took more then 15 min.
We check that the sql executoin plan changes , it showing that order of operation changed like order of using indexes is different.
Now the new plan is not good.
we want to force the old plan of sql to use in future.
I read about sql plan management , it shows a manual method to create baseline and evolve the all plan. In one texample we found that
first query execution plan was created using with out index and then with index So, second plan was good and accepted.
But in this case we do not need to change any thing ,query is performing bad may be becasue changes order of operation ..
One other way to use hint , but for this we need to change sqls , which is not possiable in production now.
The issue is
For this we need to run the sql again and oracle may not create plan like old one.So we will not be having old good plan to accept.
All 2 execution plan are already in cache .
I am looking for a way using that we can set sql plan hash value ( of good plan) or any other id of that sql plan to force to use that plan only.
any idea how to do it ..

Stored Outlines are deprecated.
OP:
To fix a specific plan you have two choices:
1. SQL Plan Baselines - assuming the "good" plan is in AWR still then the steps are along the lines of load old plan from AWR into sql tuning set using DBMS_SQLTUNE.SELECT_WORKLOAD_REPOSITORY and DBMS_SQLTUNE.LOAD_SQLSET then load plans from sqlset into sql plan baseline using DBMS_SPM.LOAD_PLANS_FROM_SQLSET.
2. Using SQL Profiles to fix the outline hints - so similar to a stored outline but using the sql profile mechanism - using the coe_xfr_sql_profile.sql script, part of an approach in Oracle support doc id 215187.1
But +1 for Nikolay's recommendation of understanding whether there is a root cause to this problem instability (plan instability being "normal", but flip flopping between "good" and "bad" being a problem). Cardinality feedback is an obvious possible influence, different peeked binds another, stat changes, etc.

Similar Messages

  • How to Force the Good Plan present in dba_hist_sql_plan for an SQL_ID

    Hi Folks
    Here i have a question on how to fix the query execution plan for which we are facing the problem. The current execution plan of the SQL ID is bad , but the execution plan in dba_hist_sql_plan or v$sql_plan is showing good one's.
    So how to force the plan_hash_value present in dba_hist_sql_plan or v$sql_plan to the current sql. Where in we cannot try using any kind of hints in the SQL so my question here , is there any way to update manually to update the plan_hash_value for the SQL_ID so that it can use the execution plan which we want to force.
    Regards,
    Phani.

    But my question is i have the good plan for the SQL_ID which is now running with the bad plan ( I am able to see the good plan in dba_hist_sql_plan view ) , my challenge here is how to force >the SQL_ID to take good plan PLAN_SQL_HASH_VALUE. Once the query is parsed and in memory I'm not aware of any way of changing the plan :(
    A day later a similar situation came up with one of our clients. I'm still not aware of any way to manually change the execution plan of an already parsed SQL but suspect histograms and/or bind peeking may be a way to explain this phenemenon
    Edited by: riedelme on Jun 18, 2010 6:13 AM

  • How to delete stored execution plan?

    Hello!
    Version: 11.1.0.7.0
    I need a function, which deletes a stored execution plan from the CBO by sql_id, to force a new hard-parse.
    Background:
    I have an application, which calles a lot of a select-statement (with bind), using a specific execution plan, lets say 'A'. This application will run and call in the next three days.
    Now, I have recalculated the statistics of the table (by DBMS_STATS.GATHER_TABLE_STATS)
    which is used for the query, to improve performance.
    Now, the exexcution plan is good (say 'B'), and the query is fast, IF I copy the sql from the OEM to (any) other tool to get the execution plan...
    But: The application still uses the plan 'A' (which still runs slow..).
    (To opposite of the documentation! see Performance Tuning Guide, Chater 13.3.1 "When statistics are updated for a database object, Oracle invalidates any currently parsed SQL statements that access the object. The next time such a statement executes, the statement is re-parsed and the optimizer automatically chooses a new execution plan based on the new statistics.")
    A short look into v$sql, v$sql_plan shows, that the application still uses the old sql_id, which has the wrong execution plan "A" stored.
    The tested statements with plan B have the same sql, but other sql_id...

    Thank you for reading!
    The solution is:
    Add parameter no_invalidate => FALSE at the gather_table_stats call:
    exec dbms_stats.gather_table_stats(ownname=>'xxxx', tabname=>'yyyy', no_invalidate=>FALSE);

  • How to corret an execution plan that shows wrong number of rows?

    Using Oracle 10gR2 RAC (10.2.0.3) on SUSE Linux 9 (x86_64).
    I have a partition table that has 5 million rows (5,597,831). However an execution plan against the table show that the table has 10 million rows.
    Execution plan:
    SELECT STATEMENT ALL_ROWS Cost : 275,751 Bytes : 443 Cardinality : 1
    3 HASH GROUP BY Cost : 275,751 Bytes : 443 Cardinality : 1
         2 PARTITION RANGE ALL Cost : 275,018 Bytes : 4,430,000,000 Cardinality : *10,000,000* Partition # : 2 Partitions accessed #1 - #6
              1 TABLE ACCESS FULL TRACESALES.TRACE_BUSINESS_AREA Cost : 275,018 Bytes : 4,430,000,000 Cardinality : 10,000,000 Partition # : 2 Partitions accessed #1 - #6
    Plan hash value: 322783426
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Pstart| Pstop |
    | 0 | SELECT STATEMENT | | 1 | 443 | 275K (2)| 00:55:10 | | |
    | 1 | HASH GROUP BY | | 1 | 443 | 275K (2)| 00:55:10 | | |
    | 2 | PARTITION RANGE ALL| | 10M| 4224M| 275K (2)| 00:55:01 | 1 | 6 |
    | 3 | TABLE ACCESS FULL | TRACE_BUSINESS_AREA | 10M| 4224M| 275K (2)| 00:55:01 | 1 | 6 |
    How does one correct the explain plan?
    The problem: Queries against the table are taking hours to complete. The problem started when the table was dropped then recreated with a new partition.
    I have complete the drop and creation against several tables for several years without problems until now.
    I have done the following: Analyzed statistics against the table, flushed buffer cache. Created a materialized view.
    However users queries are taking several hours to complete, where before the addition of the partition the queries where taking 5 minutes to complete.
    Thanks. BL.

    Yes, complete analysis of statistic was complete on indexes and against partitions.
    Table creation statement:
    CREATE TABLE TRACESALES.TRACE_BUSINESS_AREA
    ... *(400 columns)*
    TABLESPACE "trace_OLAPTS"
    PCTUSED 0
    PCTFREE 15
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 1M
    NEXT 1M
    MINEXTENTS 1
    MAXEXTENTS UNLIMITED
    PCTINCREASE 0
    BUFFER_POOL KEEP
    PARTITION BY RANGE (YEAR)
    PARTITION TRACE_06 VALUES LESS THAN ('2007')
    NOLOGGING
    NOCOMPRESS
    TABLESPACE TRACE_2006
    PCTFREE 15
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 1M
    NEXT 1M
    MINEXTENTS 1
    MAXEXTENTS UNLIMITED
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    PARTITION TRACE_07 VALUES LESS THAN ('2008')
    NOLOGGING
    NOCOMPRESS
    TABLESPACE TRACE_2007
    PCTFREE 15
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 1M
    NEXT 1M
    MINEXTENTS 1
    MAXEXTENTS UNLIMITED
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    PARTITION TRACE_08 VALUES LESS THAN ('2009')
    NOLOGGING
    NOCOMPRESS
    TABLESPACE TRACE_2008
    PCTFREE 15
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 1M
    NEXT 1M
    MINEXTENTS 1
    MAXEXTENTS UNLIMITED
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    PARTITION TRACE_09 VALUES LESS THAN ('2010')
    NOLOGGING
    NOCOMPRESS
    TABLESPACE TRACE_2009
    PCTFREE 15
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 1M
    NEXT 1M
    MINEXTENTS 1
    MAXEXTENTS UNLIMITED
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    PARTITION TRACE_10 VALUES LESS THAN ('2011')
    NOLOGGING
    NOCOMPRESS
    TABLESPACE TRACE_2010
    PCTFREE 15
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 1M
    NEXT 1M
    MINEXTENTS 1
    MAXEXTENTS UNLIMITED
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    PARTITION TRACE_11 VALUES LESS THAN (MAXVALUE)
    NOLOGGING
    NOCOMPRESS
    TABLESPACE TRACE_2011
    PCTFREE 15
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 1M
    NEXT 1M
    MINEXTENTS 1
    MAXEXTENTS UNLIMITED
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    NOCOMPRESS
    CACHE
    PARALLEL ( DEGREE DEFAULT INSTANCES DEFAULT )
    MONITORING;
    *(index statements, constraints, triggers and security)*
    Table caching is on and running in parallel degree 4 instances 1.

  • How to fix different execution plan for different bind variable values?

    Please find the below query. The execution plan is fine. The problem That I am facing is in some cases for different bind variable values execution plan gets changed and degrades performance. I have used 6 tables here and all of the tables have histogram on all columns. Database version is Oracle 10g and the value of method_opt is 'For all columns size auto'
    SELECT l.LineNumber INTO :b0
    FROM Lines l ,LineVersions lv ,Statuses s
    WHERE (((((((((((l.serviceContractId=:b1 AND l.LineId<>:b2)
    AND lv.LineId=l.LineId) AND lv.StatusId=s.StatusId)
    AND s.Code IN ('EPR','ERE','EEP','ERP','PRP','PRD','AAC'))
    AND NOT (s.CODE='AAC' AND lv.activeto<TO_DATE(:b3,:b4)))
    AND lv.EquipmentDetailId=:b5) AND lv.RouteDetailId=:b6)
    AND (lv.cargoDetailId=:b7 OR lv.cargoDetailId IN
    (SELECT i_cd1.cargoDetailId
    FROM CargoDetails i_cd1 ,CargoDetails i_cd2 ,CargoCommodities i_cc1 ,
    CargoCommodities i_cc2 WHERE
    ((((((i_cd2.cargoDetailId=:b7 AND i_cd1.cargoDetailId<>:b7)
    AND i_cd1.ServiceContractId=:b1) AND i_cd1.cargoTypeId=i_cd2.cargoTypeId)
    AND i_cc1.cargoDetailId=i_cd1.cargoDetailId)
    AND i_cc2.cargoDetailId=i_cd2.cargoDetailId)
    AND i_cc1.commodityId=i_cc2.commodityId))))
    AND ((lv.customerGroupId IS NULL AND :b11=0) OR lv.customerGroupId IN
    (SELECT cgm1.customerGroupId
    FROM CustomerGroupMembers cgm1 ,CustomerGroupMembers cgm2 ,CustomerGroups cg1
    WHERE (((cgm2.customerGroupId=:b11 AND cgm1.customerNoId=cgm2.customerNoId)
    AND cg1.CustomerGroupId=cgm1.CustomerGroupId)
    AND cg1.ServiceContractId=l.ServiceContractId)))) AND lv.linetype='C')
    AND ROWNUM=1)
    After searching in several blogs I have found the below solutions. Please see it and let me know it is correct or not
    Solution 1:-Get rid of histogram that does nothing but messes up execution plan by giving below command
    exec dbms_stats.gather_table_stats(owner, tablename, method_opt => 'for all columns size 1', cascade => true);
    As 6 tables are there I need to execute above command 6 times.
    Solution 2:- Use stored outline. Not sure how to get the best execution plan.
    I am looking for answers ASAP. Thanks in advance

    As you have probably read, bind variables and histograms do not mix well.
    Histograms suggest that you have skew in your data such that different values should get different plans
    Bind variables exist so that SQL with different supplied values can be shared.
    Mix the two together and at parse time with bind variable peeking you get plans for specific values shared for all values.
    The solutions you have mentioned are the common approaches, together with a third - use literals not binds if you've got data skew (i.e. your histograms are justified) and don't want shared SQL.
    I would have thought that getting rid of some of these histograms may be the right approach if you're none of your application SQL is using literals to benefit from them.
    Can you confirm your version of Oracle.
    Further reading:
    http://jonathanlewis.wordpress.com/2009/05/06/philosophy-1/
    http://structureddata.org/2008/03/26/choosing-an-optimal-stats-gathering-strategy/
    http://richardfoote.wordpress.com/2008/01/04/dbms_stats-method_opt-default-behaviour-changed-in-10g-be-careful/

  • How to capture the execution plan for a query

    HI All,
    Can anyone please help me in finding out the command to capture the execution plan for a query.
    Execution plan for select * from EMP where <Condtions>
    it is getting executed successfully but i need to get the proper execution plan for the same.
    Thanks

    971830 wrote:
    i want to know where execution plan gets generated??
    in PMON of server process or in shared pool??
    i know that optimixer create execution plan..It is stored in Library Cache (present inside Shared Pool ).
    select * from v$sql_plan;An absolute beautiful white paper :
    Refer this -- www.sagelogix.com/sagelogix/SearchResults/SAGE015052
    Also -- http://www.toadworld.com/KNOWLEDGE/KnowledgeXpertforOracle/tabid/648/TopicID/XPVSP/Default.aspx
    HTH
    Ranit B.

  • How to skip existing execution plan for a query

    Hi,
    I want to skip existng execution plan for a query which I am executing often. I dont want it to use the same execution plan everytime. Please let me know if any method is there skip the existing execution plan.
    Thanks in advance.......
    Edited by: 900105 on Dec 1, 2011 4:52 AM

    Change the query so it is syntactically different, but has the same semantics (meaning). That way CBO will reparse it and you might get a new execution plan.
    One simple way to do that is to add a dummy predicate ( 45=45) to the where clause. The predicate must be changed every time the query is executed ( 46=46 , 47=47 ,… ).
    Iordan Iotzov
    http://iiotzov.wordpress.com/

  • How are execution plan created with tables of stale stats

    Hello
    I would like to ask the group
    1. How oracle handels the execution plan with table joins where some tables have stale stats
    2. How would oracle handel execution plan where the table has histogram but the stats are stale.
    Database version 11.1.0.7.0
    Thanks
    Arun

    ALTER SESSION SET EVENTS='10053 trace name context forever, level 1';
    by doing above before executing the SQL, you can see what & how CBO arrives at the actual execution plan

  • Sql execution plan

    There was a query to create the execution plan for owner name.view name
    i know to generate the explain plan for sql query using
    explain plan for <sql query>
    whereas how to generate the execution plan for owner name.view name using explain plan.
    Please explain and guide me in this
    Aram

    aram wrote:
    There was a query to create the execution plan for owner name.view name
    i know to generate the explain plan for sql query using
    explain plan for <sql query>
    whereas how to generate the execution plan for owner name.view name using explain plan.
    Please explain and guide me in this
    Aramexplain plan for SELECT * FROM OWNER_NAME.VIEW;

  • How to know query execution time in sql plus

    HI
    I want to know the query execution time in sql plus along with statistics
    I say set time on ;
    set autotrace on ;
    select * from view where usr_id='abcd';
    if the result is 300 rows it scrolls till all the rows are retrieved and finally gives me execution time as 40 seconds or 1 minute.. (this is after all the records are scrolled )
    but when i execute it in toad it gives 350 milli seconds..
    i want to see the execution time in sql how to do this
    database server 11g and client is 10g
    regards
    raj

    what is the difference between .. the
    statistics gathered in sql plus something like this and the one that i get from plan_table in toad?
    how to format the execution plan I got in sqlplus in a proper understanding way?
    statistics in sqlplus
    tatistics
             0  recursive calls
             0  db block gets
           164  consistent gets
             0  physical reads
             0  redo size
         29805  bytes sent via SQL*Net to client
           838  bytes received via SQL*Net from client
            25  SQL*Net roundtrips to/from client
             1  sorts (memory)
             0  sorts (disk)
           352  rows processedexecution plan in sqlplus... how to format this
    xecution Plan
      0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=21 Card=1 Bytes=10
             03)
      1    0   HASH (UNIQUE) (Cost=21 Card=1 Bytes=1003)
      2    1     MERGE JOIN (CARTESIAN) (Cost=20 Card=1 Bytes=1003)
      3    2       NESTED LOOPS
      4    3         NESTED LOOPS (Cost=18 Card=1 Bytes=976)
      5    4           NESTED LOOPS (Cost=17 Card=1 Bytes=797)
      6    5             NESTED LOOPS (OUTER) (Cost=16 Card=1 Bytes=685)
      7    6               NESTED LOOPS (OUTER) (Cost=15 Card=1 Bytes=556
      8    7                 NESTED LOOPS (Cost=14 Card=1 Bytes=427)
      9    8                   NESTED LOOPS (Cost=5 Card=1 Bytes=284)
    10    9                     TABLE ACCESS (BY INDEX ROWID) OF 'USR_XR
             EF' (TABLE) (Cost=4 Card=1 Bytes=67)
    11   10                       INDEX (RANGE SCAN) OF 'USR_XREF_PK' (I
             NDEX (UNIQUE)) (Cost=2 Card=1)
    12    9                     TABLE ACCESS (BY INDEX ROWID) OF 'USR_DI
             M' (TABLE) (Cost=1 Card=1 Bytes=217)
    13   12                       INDEX (UNIQUE SCAN) OF 'USR_DIM_PK' (I
             NDEX (UNIQUE)) (Cost=0 Card=1)
    14    8                   TABLE ACCESS (BY INDEX ROWID) OF 'HDS_FCT'
              (TABLE) (Cost=9 Card=1 Bytes=143)
    15   14                     INDEX (RANGE SCAN) OF 'HDS_FCT_IX2' (IND
             EX) (Cost=1 Card=338)
    16    7                 TABLE ACCESS (BY INDEX ROWID) OF 'USR_MEDIA_
             COMM' (TABLE) (Cost=1 Card=1 Bytes=129)
    17   16                   INDEX (UNIQUE SCAN) OF 'USR_MEDIA_COMM_PK'
              (INDEX (UNIQUE)) (Cost=0 Card=1)
    18    6               TABLE ACCESS (BY INDEX ROWID) OF 'USR_MEDIA_CO
             MM' (TABLE) (Cost=1 Card=1 Bytes=129)
    19   18                 INDEX (UNIQUE SCAN) OF 'USR_MEDIA_COMM_PK' (
             INDEX (UNIQUE)) (Cost=0 Card=1)
    20    5             TABLE ACCESS (BY INDEX ROWID) OF 'PROD_DIM' (TAB
             LE) (Cost=1 Card=1 Bytes=112)
    21   20               INDEX (UNIQUE SCAN) OF 'PROD_DIM_PK' (INDEX (U
             NIQUE)) (Cost=0 Card=1)
    22    4           INDEX (UNIQUE SCAN) OF 'CUST_DIM_PK' (INDEX (UNIQU
             E)) (Cost=0 Card=1)
    23    3         TABLE ACCESS (BY INDEX ROWID) OF 'CUST_DIM' (TABLE)
             (Cost=1 Card=1 Bytes=179)
    24    2       BUFFER (SORT) (Cost=19 Card=22 Bytes=594)
    25   24         INDEX (FAST FULL SCAN) OF 'PROD_DIM_AK1' (INDEX (UNI
             QUE)) (Cost=2 Card=22 Bytes=594)

  • SQL Query C# Using Execution Plan Cache Without SP

    I have a situation where i am executing an SQL query thru c# code. I cannot use a stored procedure because the database is hosted by another company and i'm not allowed to create any new procedures. If i run my query on the sql mgmt studio the first time
    is approx 3 secs then every query after that is instant. My query is looking for date ranges and accounts. So if i loop thru accounts each one takes approx 3 secs in my code. If i close the program and run it again the accounts that originally took 3 secs
    now are instant in my code. So my conclusion was that it is using an execution plan that is cached. I cannot find how to make the execution plan run on non-stored procedure code. I have created a sqlcommand object with my queary and 3 params. I loop thru each
    one keeping the same command object and only changing the 3 params. It seems that each version with the different params are getting cached in the execution plans so they are now fast for that particular query. My question is how can i get sql to not do this
    by either loading the execution plan or by making sql think that my query is the same execution plan as the previous? I have found multiple questions on this that pertain to stored procedures but nothing i can find with direct text query code.
    Bob;
     

    I did the query running different accounts and different dates with instant results AFTER the very first query that took the expected 3 secs. I changed all 3 fields that i've got code for parameters for and it still remains instant in the mgmt studio but
    still remains slow in my code. I'm providing a sample of the base query i'm using.
    select i.Field1, i.Field2, 
    d.Field3  'Field3',
    ip.Field4 'Field4', 
    k.Field5 'Field5'
    from SampleDataTable1 i, 
    SampleDataTable2 k, 
    SampleDataTable3 ip,
    SampleDataTable4 d 
    where i.Field1 = k.Field1 and i.Field4 = ip.Field4 
    i.FieldDate between '<fromdate>' and  '<thrudate>' 
    and k.Field6 = <Account>
    Obviously the field names have been altered because the database is not mine but other then the actual names it is accurate. It works it just takes too long in code as described in the initial post. 
    My params setup during the init for the connection and the command.
    sqlCmd.Parameters.Add("@FromDate", SqlDbType.DateTime);
            sqlCmd.Parameters.Add("@ThruDate", SqlDbType.DateTime);
            sqlCmd.Parameters.Add("@Account", SqlDbType.Decimal);
    Each loop thru the code changes these 3 fields.
        sqlCommand.Parameters["@FromDate"].Value = dtFrom;
        sqlCommand.Parameters["@ThruDate"].Value = dtThru;
        sqlCommand.Parameters["@Account"].Value = sAccountNumber;
    SqlDataReader reader = sqlCommand.ExecuteReader();
            while (reader.Read())
                reader.Close();
    One thing i have noticed is that the account field is decimal(20,0) and by default the init i'm using defaults to decimal(10) so i'm going to change the init to 
       sqlCmd.Parameters["@Account"].Precision = 20;
       sqlCmd.Parameters["@Account"].Scale = 0;
    I don't believe this would change anything but at this point i'm ready to try anything to get the query running faster. 
    Bob;

  • Oracle Execution Plan

    Hi!
    How come the Oracle execution plan doesn't show inner select statements?
    ie:
    select s.id, (select name from anothertable where id = s.id)
    from subs s
    where s.createdate < '20-March-2005'

    Which version of database are you running?
    When you run the following query on SCOTT schema, what type of plan do you get?
    SQL> set autotrace traceonly explain
    SQL> select d.*, (select sum(sal) from emp e where e.deptno = d.deptno) from dept d ;
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=327 Bytes=981
              0)
       1    0   SORT (AGGREGATE)
       2    1     TABLE ACCESS (BY INDEX ROWID) OF 'EMP' (Cost=2 Card=3333
              3 Bytes=166665)
       3    2       INDEX (RANGE SCAN) OF 'IDX_EMP_DEPTNO' (NON-UNIQUE) (C
              ost=1 Card=33333)
       4    0   TABLE ACCESS (FULL) OF 'DEPT' (Cost=2 Card=327 Bytes=9810)
    SQL> disconnect
    Disconnected from Oracle9i Enterprise Edition Release 9.2.0.5.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.5.0 - Production
    SQL>

  • Wrh$_sql_plan - execution plan

    Hello!
    In wrh$_sql_plan I see data with sql_id that I need ,
    but there is't any row with my snap_id,
    should I consider snap_id with the first smallest number to get cuurent execution plan of statement or how to get teal execution plan of statement that
    already isn't present in cashe ?
    In other words in some interval of time DML-statement was executed ,
    it is present at the AWR report, but isn't visible in wrh$_sql_plan with my snap_id
    Thanks and regards,
    Pavel
    Edited by: Pavel on Oct 31, 2012 4:29 AM

    Dba_hist_sql_plan (Wrh$_sql_plan) does not need to pay attention to snap id.
    From a data modelling perspective, this makes sense because one particular plan may appear multiple times across multiple snaps.
    All we need is one recording of that particular plan to show what that plan is.
    What you probably want to reference is dba_hist_sqlstat which will tell you about the executions of a particular statement in a period and which plans were used.
    Edited by: Dom Brooks on Oct 31, 2012 11:59 AM

  • How can I get an execution plan for a Function in oracle 10g

    Hi
    I have:
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    CORE 10.2.0.4.0 Production
    TNS for Solaris: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    I would like to know if is possible to get an EXECUTION PLAN for a FUNCTION if so, how can I get it ?
    Regards

    You can query the AWR data if your interesting SQL consumes enough resources.
    Here is a SQL*Plus script I call MostCPUIntensiveSQLDuringInterval.sql (nice name eh?)
    You'll need to know the AWR snap_id numbers for the time period of interest, then run it like this to show the top 20 SQLs during the interval:
    @MostCPUIntensiveSQLDuringInterval 20The script outputs a statement to run when you are interested in looking at the plan for an interesting looking statement.
    -- MostCPUintesticeSQLDuringInterval: Report on the top n SQL statements during an AWR snapshot interval.
    -- The top statements are ranked by CPU usage
    col inst_no             format      999 heading 'RAC|Node'
    col sql_id              format a16      heading 'SQL_ID'
    col plan_hash_value     format 999999999999 heading 'Plan|hash_value'
    col parsing_schema_name format a12      heading 'Parsing|Schema'
    col module              format a10      heading 'Module'
    col pct_of_total   format        999.99 heading '% Total'
    col cpu_time       format   999,999,999 heading 'CPU     |Time (ms)'
    col elapsed_time   format   999,999,999 heading 'Elapsed |Time (ms)'
    col lios           format 9,999,999,999 heading 'Logical|Reads'
    col pios           format   999,999,999 heading 'Physical|Reads'
    col execs          format    99,999,999 heading 'Executions'
    col fetches        format    99,999,999 heading 'Fetches'
    col sorts          format       999,999 heading 'Sorts'
    col parse_calls    format       999,999 heading 'Parse|Calls'
    col rows_processed format   999,999,999 heading 'Rows|Processed'
    col iowaits        format   999,999,999,999 heading 'iowaits'
    set lines 195
    set pages 75
    PROMPT Top &&1 SQL statements during interval
    SELECT diff.*
    FROM (SELECT e.instance_number inst_no
                ,e.sql_id
                ,e.plan_hash_value
                ,e.parsing_schema_name
                ,substr(trim(e.module),1,10) module
                ,ratio_to_report(e.cpu_time_total - b.cpu_time_total) over (partition by 1) * 100 pct_of_total
                ,(e.cpu_time_total - b.cpu_time_total)/1000 cpu_time
                ,(e.elapsed_time_total - b.elapsed_time_total)/1000 elapsed_time
                ,e.buffer_gets_total - b.buffer_gets_total lios
                ,e.disk_reads_total - b.disk_reads_total pios
                ,e.executions_total - b.executions_total execs
                ,e.fetches_total - b.fetches_total fetches
                ,e.sorts_total - b.sorts_total sorts
                ,e.parse_calls_total - b.parse_calls_total parse_calls
                ,e.rows_processed_total - b.rows_processed_total rows_processed
    --            ,e.iowait_total - b.iowait_total iowaits
    --            ,e.plsexec_time_total - b.plsexec_time_total plsql_time
          FROM dba_hist_sqlstat b  -- begining snap
              ,dba_hist_sqlstat e  -- ending snap
          WHERE b.sql_id = e.sql_id
          AND   b.dbid   = e.dbid
          AND   b.instance_number = e.instance_number
          and   b.plan_hash_value = e.plan_hash_value
          AND   b.snap_id = &LowSnapID
          AND   e.snap_id = &HighSnapID
          ORDER BY e.cpu_time_total - b.cpu_time_total DESC
         ) diff
    WHERE ROWNUM <=&&1
    set define off
    prompt  to get the text of the SQL run the following:
    prompt  @id2sql &SQL_id
    prompt .
    prompt  to obtain the execution plan for a session run the following:
    prompt  select * from table(DBMS_XPLAN.DISPLAY_AWR('&SQL_ID'));
    prompt  or
    prompt  select * from table(DBMS_XPLAN.DISPLAY_AWR('&SQL_ID',NULL,NULL,'ALL'));
    prompt .
    set define on
    undefine LowSnapID
    undefine HighSnapIDI guess you'll need the companion script id2sql.sql, so here it is:
    set lines 190
    set verify off
    declare
       maxDisplayLine  NUMBER := 150;  --max linesize to display the SQL
       WorkingLine     VARCHAR2(32000);
       CurrentLine     VARCHAR2(64);
       LineBreak       NUMBER;
       cursor ddl_cur is
          select sql_id
            ,sql_text
          from v$sqltext_with_newlines
          where sql_id='&1'
          order by piece
       ddlRec ddl_cur%ROWTYPE;
    begin
       WorkingLine :='.';
       OPEN ddl_cur;
       LOOP
          FETCH ddl_cur INTO ddlRec;
          EXIT WHEN ddl_cur%NOTFOUND;
          IF ddl_cur%ROWCOUNT = 1 THEN
             dbms_output.put_line('.');
             dbms_output.put_line('   sql_id: '||ddlRec.sql_id);
             dbms_output.put_line('.');
             dbms_output.put_line('.');
             dbms_output.put_line('SQL Text');
             dbms_output.put_line('----------------------------------------------------------------');
          END IF;
          CurrentLine := ddlRec.sql_text;
          WHILE LENGTH(CurrentLine) > 1 LOOP
             IF INSTR(CurrentLine,CHR(10)) > 0 THEN -- if the current line has an embeded newline
                WorkingLine := WorkingLine||SUBSTR(CurrentLine,1,INSTR(CurrentLine,CHR(10))-1);  -- append up to new line
                CurrentLine := SUBSTR(CurrentLine,INSTR(CurrentLine,CHR(10))+1);  -- strip off up through new line character
                dbms_output.put_line(WorkingLine);  -- print the WorkingLine
                WorkingLine :='';                   -- reset the working line
             ELSE
                WorkingLine := WorkingLine||CurrentLine;  -- append the current line
                CurrentLine :='';  -- the rest of the line has been processed
                IF LENGTH(WorkingLine) > maxDisplayLine THEN   -- the line is morethan the display limit
                   LineBreak := instr(substr(WorkingLine,1,maxDisplayLine),' ',-1); --find the last space before the display limit
                   IF LineBreak = 0 THEN -- there is no space, so look for a comma instead
                      LineBreak := substr(WorkingLine,instr(substr(WorkingLine,1,maxDisplayLine),',',-1));
                   END IF;
                   IF LineBreak = 0 THEN -- no space or comma, so force the line break at maxDisplayLine
                     LineBreak := maxDisplayLine;
                   END IF;
                   dbms_output.put_line(substr(WorkingLine,1,LineBreak));
                   WorkingLine:=substr(WorkingLine,LineBreak);
                END IF;
             END IF;
          END LOOP;
          --dbms_output.put(ddlRec.sql_text);
       END LOOP;
       dbms_output.put_line(WorkingLine);
       dbms_output.put_line('----------------------------------------------------------------');
       CLOSE ddl_cur;
    END;
    /

  • How to get execution plan in a CLOB?

    Hello,
    I want to get execution plans of a query in a CLOB format. I am trying to run following query against v$sql view. One of the columns I want is the execution plan for the query. I am getting following error. Eventually, I am going to insert this data into a log table to keep history of all SQLs and their execution plans.
    How can I do that?
    Thank you in advance.
    SQL> SELECT sql_id,
      2         plan_hash_value,
      3         TO_CLOB (DBMS_XPLAN.display_awr (sql_id            => sql_id,
      4                                          plan_hash_value   => plan_hash_value,
      5                                          format            => '+PEEKED_BINDS'))
      6            sql_plan_clob,
      7         buffer_gets,
      8         executions
      9    FROM v$sql
    10   WHERE ROWNUM < 5;
           TO_CLOB (DBMS_XPLAN.display_awr (sql_id            => sql_id,
    ERROR at line 3:
    ORA-00932: inconsistent datatypes: expected NUMBER got SYS.DBMS_XPLAN_TYPE_TABLE

    try first
    select *
      from table(DBMS_XPLAN.display_awr(sql_id          => sql_id,
                                        plan_hash_value => plan_hash_value,
                                        format          => '+PEEKED_BINDS'
                )to see the table returned
    then try to adapt http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:68212348056 to produce fixed length rows.
    look for describe_columns procedures in http://docs.oracle.com/cd/E11882_01/appdev.112/e25788/d_sql.htm#i1025449 for column length information available in internal tables and write the rows directly to clob instead of writing to disk and loading your clob from there.
    Regards
    Etbin
    Edited by: Etbin on 31.10.2012 19:56
    pointing to dbms_sql package added

Maybe you are looking for

  • Problem with af:poll in IE

    In my searchpage, i've <af:poll> which will show the timer once the user selects some rows from resultstable and clicks "submit". The timer will run till some processing is done . Intermittently, i face the foll issue in IE but not in Mozilla.Sometim

  • How To Get PREVIEW on Television while in Timeline?

    I have a datavideo analog convertor I use to watch playback on my television from FCP. When I use Print To Video it will show up fine but I also used to be able to just play through the timeline and view on my TV as well. For some reason that option

  • Pavillion 500-c60 Windows 7 x64 backload hints

    Just trying to give back, not perfect: 1)  Win 8.1 Home doesn't have downgrade rights. 2)  If you have a valid Win7 license, then this is what I did: 3)  Don't plug in the network.  Boot the PC and build the recovery DVDs (4). 4)  Restart the PC and

  • I cannot open mp3 files I received from a purchased download. They are in a .zip file but no matter what I do, they cannot be opened. Please help.

    I have right clicked and selected open, and the loading ring shows but nothing happens. I have also extracted the files, opened them in itunes and windows media player. (cannot be accesed in itunes or wmp)

  • Display dead ?

    Hi, my N900 ran out of power and after a hours (actually i left the device on my desk over night) i recharged the device - but Problem is that it seems the Display is not working or not even starting (not sure which one of this 2 When i turn on the d