Query Cost vs SQL statistics

I have a query and when I execute it it gives a cost of 4000+, however after I optimized it came down to about 300 or so.
My problem is that after discussing the query with my manager he showed me that the statistics of the first query version where better than the second one (we made sure it was not cached ).
How come that the second one runs faster and has less cost even if the SQL statistics is worse?
example:
first query:
cost: 4000
time to run: 2:00+ minutes
1 recursive call
1310 consistent gets
2600 physical reads
second query:
cost: 290
time to run: ~1:30 minutes
1200 recursive calls
13000 consistent gets
30000 physical read

user8973401 wrote:
I have a query and when I execute it it gives a cost of 4000+, however after I optimized it came down to about 300 or so.
How come that the second one runs faster and has less cost even if the SQL statistics is worse?
example:
first query:
cost: 4000
time to run: 2:00+ minutes
1 recursive call
1310 consistent gets
2600 physical reads
second query:
cost: 290
time to run: ~1:30 minutes
1200 recursive calls
13000 consistent gets
30000 physical readI personally use execution time along with the metrics you listed together to determine when one version of a query is better than another. There are gray areas like the situation you listed where "better" is hard to determine. Another useful metric is CPU, which AUTOTRACE does not list but can be found using V$SQL, traces, or AWR reports. Sometimes the biggest challenge is making sure the result set of the tuned query is the same as the original one ;)
You listed mixed results which can happen. The run time was 2 minutes vs 1:30 but other metrics were higher. The CPU on the first query might be lower.
Oh, it DOES happen that a higher-cost version of a query executes faster and uses fewer resources than a lower-cost version. Remember that the COST is an estimate which is usally but not alway accurate

Similar Messages

  • SQL Query Cost Report..

    Hi all,
    I am novice to OEM. I wanted to do / run sql query cost report.. How can i do it in OEM.?? Is it possible to do in OEM..??? Please guide me to solve this problem.??
    Your suggestion will be helpful.
    Thanks,
    -Mahesh.

    Hi,
    Thanks for your reply, but I want info about Oracle Enterprise Manager 10g.
    Actual requirement is like this,
    We have script files written in Linux Shell scripts, which are related to DB activities like Startup DB, Shutdown DB, perfstat, checking free space etc etc. These we want to migrate into OEM using OEM built-in features, few of which we've already migrated. We have analyzed scripts. One of the script is for SQL Query Cost Report (Which i didn't get what it does..)
    So is there any option/inbuilt feature through which we can do "SQL Cost Report".
    Once again thanks for your reply.
    -Mahesh.

  • How query cost and execution time are releated ?

    hi experts,
      i am curious to know, how the query cost and execution time is related?
     Query taking less time ,query cost is 65%, but query taking more time but query cost is 0%.
    how to connect both and improve query performance.
    Thanks

    i think you are refering to cost (relative to the batch) execution 65%, where there are more that one statement, it may compare the cost of each statement with in the batch
    i assume it mainly take subtree cost and IO stat as cost, but in some cases i may wrong when there is multi line function and many other facter influence the cost, and i would say it depends on the query
    cost is unit-less
    The reason these costs exist is because of the query optimization SQL Server does: it does cost-based optimization, which means that the optimizer formulates a lot of different ways to execute the query, assigns a cost to each of these alternatives, and
    chooses the one with the least cost. The cost tagged on each alternative is heurestically calculated, and is supposed to roughly reflect the amount of processing and I/O this alternative is going to take.
    refer :
    http://blogs.msdn.com/b/sqlqueryprocessing/archive/2006/10/11/what-is-this-cost.aspx
    Thanks
    Saravana kumar C

  • Query cost and CASE statement

    Hi, I'm working on a performance issue for a customer.
    I'm tuning some suspect SQL that uses complex DECODE statements to perform IF/THEN/ELSE logic.
    I've taken a statement and rewritten it using CASE however what I've noticed is the cost of the query execution plan has increased dramatically as a result. N.B. I haven't changed the WHERE clause of the query as yet, just replaced one DECODE with the equivalent CASE.
    The db version is 9.2.0.4. Does anyone know of issues with the performance of CASE as opposed to DECODE. I'm wondering should I leave the DECODEs as is even though they're way too complicated.
    Tks,
    Paul.

    Here's an example of a DECODE:
    nvl(count(distinct decode
    (decode(sign(ords.dwh_created_date_id-:v_start_cycle_id),1,1,0,1,-1,0) *
    decode(sign(:v_end_cycle_id-ords.dwh_created_date_id),1,1,0,1,-1,0),1,ords.dwh_order_id,NULL)),0) calc1
    The equivalent CASE I've coded is:
    NVL(COUNT(DISTINCT(CASE WHEN (ords.dwh_created_date_id BETWEEN :v_start_cycle_id AND :v_end_cycle_id)
    THEN
    ords.dwh_order_id
    ELSE
    NULL
    END)),0) calc1
    I've been doing further testing with an amended WHERE clause and did run both CASE and DECODE versions. The performance difference between the two was negligible. So it seems (as I'd hoped) that the amendment of the execution path doesn't appear to be affected by CASE even though Oracle reports the query cost of it is higher.
    It is slightly confusing though. Is the query cost in this case a red herring ?

  • Query help in sql commands

    using apex 4.1 i'm entering the following query in the sql command window and I keep getting a pop-up for Entering Bind Variable. I'm not using bind variables though, anyone else see this issue before?
    SELECT A.FIRST,A.LAST,A.COMPANY AS CNAME,
    J.TOT_MAN_HOURS,
    J.ACREAGE,
    W.NUM_WORKERS,
    W.START_DT
    FROM EW_ACCOUNTS A, EW_WORK_ORDER W, EW_JOBS J
    WHERE A.ID = J.ACCT_ID
    AND J.JOB_ID = W.JOB_ID
    AND W.START_DT >= SYSDATE
    AND W.START_DT < SYSDATE+1
    ORDER BY W.START_DT

    I tried that and it didn't seem to help either.
    Funny though, if I write a new query against just one of the tables and write out each column name. it works. If I use the * instead of writing each column name, I have the same issue.
    This is in apex.appshosting.com free demo environment. I sent them an email asking about it and they told me it was a code issue and they don't support the demo environment.

  • Query in pl/sql oracle

    Hi All!
    I want to write following type of query in PL/SQL
    How can I write one which will work.
    <B>
    SELECT count(1) INTO v_count2 from TRJ_TRAN_REJ_T a and PEU_PUR_ENRL_UNT_T b
    where a.TRJ_CVRG_PER_DATE IN (b.PEU_EFF_DATE AND b.PEU_END_DATE) AND
    a.purik = b.purik AND a.peuik = b.peuik
    <B>
    Above query is not working correctly. Any changes?? DATE stored in database is like 01/01/2001
    v_count2 is NUMBER variable declared in PL?SQL.
    SA

    You don't need to use a PL/SQL, a simple SQL will suffice. I guess you could write it as a function?
    I think your SQL was wrong so I took the liberty of fixing it for you. You seperate tables with commas in a FROM clause, not AND.
    Anyway, on the lines of a SQL Statement you can do the following.
    SELECT     count(1) AS mycount
    FROM     TRJ_TRAN_REJ_T a,
         PEU_PUR_ENRL_UNT_T b
    WHERE     a.TRJ_CVRG_PER_DATE IN (b.PEU_EFF_DATE AND b.PEU_END_DATE)
    AND     a.purik = b.purik
    AND     a.peuik = b.peuik
    Connection conn = DriverManager.getConnection(URL, username, password);
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery( your sql);
    while ( rs.next() )
         int mycount = rs.getInt("mycount");
    close stuff down here

  • Query in PL/SQL Help

    Hi All!
    I want to write following type of query in PL/SQL
    How can I write one which will work.
    SELECT count(1) INTO v_count2 from TRJ_TRAN_REJ_T a and PEU_PUR_ENRL_UNT_T b
    where a.TRJ_CVRG_PER_DATE IN (b.PEU_EFF_DATE AND b.PEU_END_DATE) AND
    a.purik = b.purik AND a.peuik = b.peuik
    Above query is not working correctly. Any changes?? DATE stored in database is like 01/01/2001
    v_count2 is NUMBER variable declared in PL?SQL.
    SA

    I'd also watch out for the TIME part of the date matching, best to do a TRUNC on them, but make sure also [purik] and [peuik] are indexed. This is the format I use for a select. Some parts were removed but you get the idea.
    --[START]
    --[SELECT]
    SELECT
    --/*+ choose */
    /*+ RULE */
    --/*+ first_rows */
    --/*+ all_rows */
    count(1)          --[C1]
    --[INTO]
    INTO
    v_count2          --[V1]
    --[FROM]
    FROM
    trj_tran_rej_t T1,
    peu_pur_enrl_unt_t T2
    --[WHERE]
    WHERE
    TRUNC(T1.trj_cvrg_per_date) = TRUNC(T2.peu_eff_date)
    OR
    TRUNC(T1.trj_cvrg_per_date) = TRUNC(T2.peu_end_date)
    AND
    T1.purik = T2.purik
    AND
    T1.peuik = T2.peuik
    --[ABORT]
    AND 1=1;
    --[END]
    Tyler Durden

  • Query cost is changing when used in a VO

    Hi All
    I have created the view with the below query
    SELECT component_item_name segment1,component_item_id inventory_item_id,organization_id,assembly_item_id
    FROM BOMFG_BOM_COMPONENTS WHERE organization_id = :1
    AND NVL(END_EFFECTIVE_DATE,SYSDATE ) >= SYSDATE
    AND EXISTS
    ( SELECT 1
    FROM apps.fnd_common_lookups fcl, mtl_system_items_b msi
    WHERE fcl.lookup_type = 'ITEM_TYPE' AND msi.item_type = fcl.lookup_code
    AND msi.inventory_item_id = component_item_id AND msi.organization_id = :2
    AND msi.item_type IN ('ATO','OPTIONAL FEAT')
    ) START WITH assembly_item_id = :3 CONNECT BY PRIOR component_item_id =assembly_item_id GROUP BY component_item_name,component_item_id,organization_id,assembly_item_id
    The cost of the above query is just 13 .
    attached this VO with one LOV in my page.
    when query gets executed while openign the page , the OA Framework is taking above query as
    select * from (SELECT component_item_name segment1,component_item_id inventory_item_id,organization_id,assembly_item_id
    FROM BOMFG_BOM_COMPONENTS WHERE organization_id = :1
    AND NVL(END_EFFECTIVE_DATE,SYSDATE ) >= SYSDATE
    AND EXISTS
    ( SELECT 1
    FROM apps.fnd_common_lookups fcl, mtl_system_items_b msi
    WHERE fcl.lookup_type = 'ITEM_TYPE' AND msi.item_type = fcl.lookup_code
    AND msi.inventory_item_id = component_item_id AND msi.organization_id = :2
    AND msi.item_type IN ('ATO','OPTIONAL FEAT')
    ) START WITH assembly_item_id = :3 CONNECT BY PRIOR component_item_id =assembly_item_id GROUP BY )component_item_name,component_item_id,organization_id,assembly_item_id
    and the query cost becomes 21000 .
    Because of this, VO takes longer than expected time .
    pls suggest how can I handle this ,
    Thanks
    Naveen
    Edited by: user640347 on Mar 10, 2010 12:27 AM

    Hi,
    Just tell me one thing you execute the query at backend after providing the inputs.
    now again after the page has loaded and then again execute the lov query at backend with same input
    variables.
    Now if the query is same then how can the cost differ?
    Verify it.
    Thanks,
    Gaurav

  • Wrong query in pl/sql

    Good Morning,
    i have a string containing a query in pl/sql :
    description varchar2(100) := 'select adeia_id||description,adeia_id from mis_adeia where plafon=1';
    which selects adeia_id and description fron a table and displays them together, but i want to seperate adeia_id and description with a blank or a dot, so i change the string and make it like:
    description varchar2(100) := 'select adeia_id||' || ' ' || 'description,adeia_id from mis_adeia where plafon=1';
    am i doing something wrong?
    thanks for reading.

    thank you peter but it doesn't work. i tried it. the string i pass it as argument in the create_group_from_query function in forms builder, and when i use double quots it gives me the error, that cannot create the group! i don't know what is the fault.

  • Query in PL/SQL code is slower

    I have a very strange issue within my development database, I'm using Oracle 10g.
    I created a query to read some data from a large collection of tables -OFDM tables- I have tested and tuned the performance of the query from (PL/SQL Developer 7 ), it takes only 2 minutes to finish but when I use the same query as a cursor in a database procedure it consume a lot of time around 15 min to get the data.
    Your help is appreciated

    [url http://groups.google.de/group/comp.databases.oracle.server/browse_frm/thread/df893cf9be9b2451/54f9cf0e937d7158?hl=de&tvc=1&q=%22Beautified%22+code+runs+slower#54f9cf0e937d7158]Recently somebody complained about slow performance after code was beatified in PL SQL Developer, after recompilation without flag "Add Debug Information" it run faster...
    (just a guess)
    Best regards
    Maxim

  • Re: How to converting from PL/SQL query to T-SQL query

    How to converting from PL/SQL query to T-SQL query... Its Urgent

    Download the
    SQL Server Migration Assistant for Oracle.  It will convert whole Oracle databases, or single queries or PL/SQL stored procedures.
    With caution that If your database is using Collation which is case sensitive SSMA will not work.SSMA doesnt guarantees 100% for conversion of Queries/stored proc /database if it fails to do so for some queries you will have to do it manually.
    But you can try
    Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers

  • Data discrepancy between Webi Report and same Query fired on SQL Server 2k5

    Hi ,
    We are facing an issue in BO XI R2.
    We need to run a Webi report in which negative values for forecasting data for year 2011 and 2012 should be displayed.
    When we are running this report for negative values, we are getting message u2018There is no data corresponding to this queryu2019.
    Then we tried executing the same query on Database. Here at db level we got the correct required result.
    So now we are not able to find the reason for data discrepancy .
    Why the same query generated by Webi is providing correct data when fired on reporting database and not when running the Webi Report.
    Checklist we have gone through for this troubleshooting is-
    -Connections of Universe (Is universe pointing to same database or not)
    -Any filter condition present at universe level and at report level.
    Could anyone please help on this.
    Regards,
    Vaibhav

    Vaibhav,
    Have you tried the following when you are in WebI: go under the Edit Query panel, click on the "SQL" icon, and review the query that is getting generated?  At this point you can also click on the "copy" option, then paste this query into your SQL application analyzer and run to see what results are generated.  To me, it sounds like the portion trying to generate the "minus" sign might be getting tripped up causing the disconnect....
    Thanks,
    John

  • Crosstab query using pure SQL only

    Hi all,
    Found a lot of threads on crosstab, but none seems to address what I need. I need to perform crosstab query using pure SQL only & the number of columns are dynamic. From a query, I obtained the below table:
    Name Date Amount
    Alex 2005-06-10 1000
    Alex 2005-06-20 1000
    Alex 2005-07-10 1000
    Alex 2005-07-20 1000
    Alex 2005-08-10 1000
    Alex 2005-08-20 1000
    John 2005-06-10 2000
    John 2005-06-20 2000
    John 2005-07-10 2000
    John 2005-07-20 2000
    John 2005-08-10 2000
    John 2005-08-20 2000
    And I need to transform it into:
    Name 06-2005 07-2005 08-2005
    Alex 2000 2000 2000
    John 4000 4000 4000
    Reason for the columns being dynamic is because they'll be a limit on the date ranges to select the data from. I'd have a lower & upper bound date say June-2005 to August-2005, which explains how I got the data from the above table.
    Please advise.
    Thanks!

    Hi,
    I couldn't resist the intellectual challenge of a pure SQL solution for a pivot table with a dynamic number of columns. As Laurent pointed out, a SQL query can only have a fixed number of columns. You can fake a dynamic number of columns, though, by selecting a single column containing data at fixed positions.
    <br>
    <br>
    If it were me, I'd use a PL/SQL solution, but if you must have a pure SQL solution, here is an admittedly gruesome one. It shows the sum of all EMP salaries per department over a date range defined by start and end date parameters (which I've hardcoded for simplicity). Perhaps some of the techniques demonstrated may help you in your situation.
    <br>
    <br>
    set echo off
    set heading on
    set linesize 100
    <br>
    select version from v$instance ;
    <br>
    set heading off
    <br>
    column sort_order noprint
    column sal_sums format a80
    <br>
    select -- header row
      1        as sort_order,
      'DEPTNO' as DEPTNO ,
      sys_connect_by_path
        ( rpad
            ( to_char(month_column),
              10
          ' | '
        ) as sal_sums
    from
        select
          add_months( first_month, level - 1 ) as month_column
        from
          ( select
              date '1981-01-01' as first_month,
              date '1981-03-01' as last_month,
              months_between( date '1981-03-01', date '1981-01-01' ) + 1 total_months
            from dual
        connect by level < total_months + 1
      ) months
    where
      connect_by_isleaf = 1
    connect by
      month_column = add_months( prior month_column, 1 )
    start with
      month_column = date '1981-01-01'
    union all
    select -- data rows
      2 as sort_order,
      deptno,
      sys_connect_by_path( sum_sal, ' | ' ) sal_sums
    from
      select
        dept_months.deptno,
        dept_months.month_column,
        rpad( to_char( nvl( sum( emp.sal ), 0 ) ), 10 ) sum_sal
      from
          select
            dept.deptno,
            reporting_months.month_column
          from
            dept,
            ( select
                add_months( first_month, level - 1 ) as month_column
              from
                ( select
                    date '1981-01-01' as first_month,
                    date '1981-03-01' as last_month,
                    months_between( date '1981-03-01', date '1981-01-01' ) + 1 total_months
                  from
                    dual
              connect by level < total_months + 1
            ) reporting_months
        ) dept_months,
        emp
      where
        dept_months.deptno = emp.deptno (+) and
        dept_months.month_column = trunc( emp.hiredate (+), 'MONTH' )
      group by
        dept_months.deptno,
        dept_months.month_column
    ) dept_months_sal
    where
      month_column = date '1981-03-01'
    connect by
      deptno = prior deptno and
      month_column = add_months( prior month_column, 1 )
    start with
      month_column = date '1981-01-01'
    order by
      1, 2
    <br>
    VERSION
    10.1.0.3.0
    <br>
    DEPTNO      | 81-01-01   | 81-02-01   | 81-03-01
    10          | 0          | 0          | 0
    20          | 0          | 0          | 0
    30          | 0          | 2850       | 0
    40          | 0          | 0          | 0
    <br>
    Now, if we substitute '1981-03-01' with '1981-06-01', we see 7 columns instead of 4
    <br>
    DEPTNO      | 81-01-01   | 81-02-01   | 81-03-01   | 81-04-01   | 81-05-01   | 81-06-01
    10          | 0          | 0          | 0          | 0          | 0          | 2450
    20          | 0          | 0          | 0          | 2975       | 0          | 0
    30          | 0          | 2850       | 0          | 0          | 2850       | 0
    40          | 0          | 0          | 0          | 0          | 0          | 0
    <br>To understand the solution, start by running the innermost subquery by itself and then work your way outward.

  • Edit query results in SQL worksheet

    I can't edit query results in SQL worksheet, I not found any options to "ON" this. I use SQL Developer 2.1.1.64.

    You can't edit results in the worksheet. It's an accepted feature request with no scheduled date. In the mean time you have to go to the table or write an update statement.

  • NVARCHAR (MAX) TO PRINT DYNAMIC SQL QUERY TO A SQL FILE

    Hi 
    I have a requirement where i need to write an SP which would construct a huge query using dynamic SQL and save the Dynamic query to a file. 
    The Dynamic SQL Variable I am using as @NVARCHAR(MAX) but since the query being built is large (>4000 characters), I am not able to select it into a table. PRINT @SQL prints the whole query but SELECT @SQL prints only upto 4000 characterrs. 
    And I need to save this huge dynamix sql to a file using the SP.
    Any thoughts as to how i can achieve this?
    Rajiv

    This is a know problem with dynamic SQL nvarchar(max) concatenation.
    See below for correct assembly of large SQL strings:
    CREATE table #temp(qry nvarchar(max));
    declare @cmd nvarchar(max);
    SELECT @cmd=CONCAT(CONVERT(nvarchar(max),N'SELECT '),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),N'FROM SYS.TABLES'));
    insert into #temp SELECT @cmd;
    select * from #temp;
    select len(qry), datalength(qry) from #temp;
    -- 16022 32044
    drop table #temp;
    Dynamic SQL:  http://www.sqlusa.com/bestpractices/dynamicsql/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

Maybe you are looking for