How to tune a query

how to tune a query . what are the procedures?

Following are the steps
1. Learn about RDBMS.
2. Learn how Oracle works. Oracle Architecture and other stuff.
3. Learn how SQL works (because parsing makes difference)
4. Learn about the tools provided by oracle for tuning (explain plan, sqltrace, tkprof etc.)
One you have all these knowledge. You are all set for tuning.
Thanks,
Karthick.

Similar Messages

  • How to tune this query for the improve performance ?

    Hi All,
    How to tune this query for the improve performance ?
    select a.claim_number,a.pay_cd,a.claim_occurrence_number,
    case
    when sum(case
    when a.payment_status_cd ='0'
    then a.payment_est_amt
    else 0
    end
    )=0
    then 0
    else (sum(case
    when a.payment_status_cd='0'and a.payment_est_amt > 0
    then a.payment_est_amt
    else 0
    end)
    - sum(case
    when a.payment_status_cd<>'0'
    then a.payment_amt
    else 0
    end))
    end as estimate
    from ins_claim_payment a
    where a.as_of_date between '31-jan-03' and '30-aug-06'
    and ( a.data_source = '25' or (a.data_source between '27' and '29'))
    and substr(a.pay_cd,1,1) IN ('2','3','4','8','9')
    group by a.claim_number, a.pay_cd, a.claim_occurrence_number
    Thank you,
    Mcka

    Mcka
    As well as EXPLAIN PLAN, let us know what proportion of rows are visited by this query. It may be that it is not using a full table scan when it should (or vice versa).
    And of course we'd need to know what indexes are available, and how selective they are for the predicated you have in this query ...
    Regards Nigel

  • How do tune sql query? Can somebody help me in this? Atleast prescribe book

    how do tune sql query? Can somebody help me in this? Atleast prescribe a reference book.
    I am not able understand How to analyze tkproof output.

    Check out asktom.oracle.com
    Lot's of threads on interpreting tkprof output - no simple easy solution here.
    You need to understand what is happening and THINK. Then you can be a good engineer.
    As for good books...
    Tom Kyte's books are really, really good.
    http://www.amazon.com/Effective-Oracle-Design-Osborne-ORACLE/dp/0072230657/ref=sr_1_3?ie=UTF8&s=books&qid=1266783471&sr=8-3
    http://www.amazon.com/Expert-Oracle-Database-Architecture-Programming/dp/1590595300/ref=sr_1_1?ie=UTF8&s=books&qid=1266783471&sr=8-1
    Good luck!

  • How to tune the query...?

    Hi all,
    I am having a table with millions of records and the query is taking hours
    time. How to tune the query apart from doing the following things.
    1. Creating or Deleting indexes.
    2. Using Bind variables.
    3. Using Hints.
    4. Updating the Statitics regurarly.
    Actually, i have asked this question in interview how to tune the query.
    I told him the above 4 things. Then he told, these are not working, then
    how you will tune this query.
    Thanks in advance,
    Pal

    user546710 wrote:
    Actually, i have asked this question in interview how to tune the query.
    I told him the above 4 things. Then he told, these are not working, then
    how you will tune this query.It actually depends on the scenario/problem given.
    You may want to read this first.
    When your query takes too long ...
    When your query takes too long ...
    HOW TO: Post a SQL statement tuning request - template posting
    HOW TO: Post a SQL statement tuning request - template posting

  • How to tune sql query

    Hi,
    How I can tune sql query? what are the steps for tuning.

    First important step: Infomation gathering. One part can be learning to use the powerful search engine. E.g. search this forum for: "When your query takes too long".
    Second step: Information processing. Check the data you found and apply it to your problem
    Third step: Testing. Compare the result of the applied change before and after. Was there any performance gain as expected?

  • How to tune a query which contains "Bulk Collect Into" clause

    I want to tune the below query:
    SELECT customer_master_num,
    product_nam
    BULK COLLECT INTO t_cont09_rec
    FROM TB_CMA009_SUPRA_RE_AGNT_CONT
    WHERE re_agent_customer_master_num = p_63cust_master_num
    AND customer_master_num = p_63board_master_num
    AND cancellation_dt IS NULL
    AND NVL (is_training_key_flg, 'N') = 'N';
    This contains "Bulk Collect Into" clause.
    TYPE cont09cur IS RECORD (
    customer_master_num TB_CMA009_SUPRA_RE_AGNT_CONT.customer_master_num%TYPE,
    product_nam TB_CMA009_SUPRA_RE_AGNT_CONT.product_nam%TYPE);
    t_cont09_rec cont09_rec;
    "t_cont09_rec" This is of Record Type
    Please help me out how to tune this one.

    [url http://forums.oracle.com/forums/thread.jspa?threadID=501834&tstart=0]When your query takes too long ...
    Also, don't get too distracted by the PL/SQL bulk collect into construction. If it takes time, then you have more than 99% chance that the time is spent in the SQL.
    Regards,
    Rob.

  • How to tune the query for duplicate records while joining the two tables

    hi,i am executing the query which has retrieving multiple tables,in which one of them has duplicate record,how to get single record

    Not enough info...subject says "tune" the query, message says "write" the query...and where is actual query that you had tried ?

  • How to tune the query and difference between CBO AND RBO.. Which is good

    Hello Friends,
    Here are some questions I have pls reply back with complete description and url if any ..
    1)How Did you tune Query,
    2)What approach you take to tune query? Do you use Hints?
    3)Where did you tune the query and what are the issue with query?
    4)What is difference between RBO and CBO? where u use RBO and CBO.
    5)Give some information about hash join?
    6) Using explain plan how do u know where the bottle neck in query .. how u will identify where the bottle neck is from explain plan .
    thanks/Kumar

    Hi,
    kumar73 wrote:
    Hello Friends,
    Here are some questions I have pls reply back with complete description and url if any ..
    1)How Did you tune Query, Use EXPLAIN PLAN to see exactly where it is spending its time, and address those areas.
    See the forum FAQ
    SQL and PL/SQL FAQ
    "3. How to improve the performance of my query?"
    2)What approach you take to tune query? Do you use Hints?Hints can help.
    Even more helpful is writing the SQL efficiently (avoiding multiple scans of the same table, filtering early, using built-in rather than user-defined functions, ...), creating and using indexes, and, for large tables, partitioning.
    Table design can have a big impact on performace.
    Look for ways to do part of what you need before the query. This includes denormalizing (when appropriate), the kind of pre-digesting that often takes place in data warehouses, function-based indexes, and, starting in Oracle 11, virtual columns.
    3)Where did you tune the query and what are the issue with query?Either this question is a vague summary of the entire thread, or I don't understand it. Can you re-phrase this part?
    4)What is difference between RBO and CBO? where u use RBO and CBO.Basically, use RBO if you have Oracle 7 or earlier.

  • How to tune this query

    Hi,
    Im trying to select the latest set of data from a table using a simple query for inserting into a new table.
    Details are given below.
    There are no indices for the table. Its taking around 18 sec.
    Pls advice on how to proceed so that I can bring down this time.
    Query:
    SELECT
    FROM
    M_UNDR M
    WHERE
    M.M_DATE = (SELECT MAX(M_DATE) FROM M_UNDR M1)
    AND
    M.M_TIME =
    SELECT MAX(M_TIME) FROM M_UNDR M2 WHERE M2.M_DATE = M.M_DATE
    AND
    M.U_TYPE NOT IN ('USD', 'GBP', 'EUR');
    SQL> select count(1) from m_undr;
      COUNT(1)
       2695446
    SQL>
    Version:
    SQL> select banner from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bi
    PL/SQL Release 10.2.0.3.0 - Production
    CORE    10.2.0.3.0      Production
    TNS for Solaris: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    Explain plan
    PLAN_TABLE_OUTPUT
    | Id  | Operation            | Name           | Rows  | Bytes | Cost  |
    |   0 | SELECT STATEMENT     |                |     1 |    95 | 19060 |
    |   1 |  HASH JOIN           |                |     1 |    95 | 12882 |
    |   2 |   VIEW               | VW_SQ_1        |   508 | 11176 |  6608 |
    |   3 |    HASH GROUP BY     |                |   508 | 10668 |  6608 |
    |   4 |     TABLE ACCESS FULL| M_UNDR |  2392K|    47M|  6186 |
    |   5 |   TABLE ACCESS FULL  | M_UNDR |  5594 |   398K|  6274 |
    |   6 |    SORT AGGREGATE    |                |     1 |     8 |       |
    |   7 |     TABLE ACCESS FULL| M_UNDR |  2392K|    18M|  6178 |
    SQL> sho parameter optimizer
    NAME                                 TYPE        VALUE
    optimizer_dynamic_sampling           integer     2
    optimizer_features_enable            string      10.2.0.3
    optimizer_index_caching              integer     0
    optimizer_index_cost_adj             integer     200
    optimizer_mode                       string      ALL_ROWS
    optimizer_secure_view_merging        boolean     TRUE
    SQL> sho parameter DB_FILE_MULTI
    NAME                                 TYPE        VALUE
    db_file_multiblock_read_count        integer     16
    SQL> show parameter db_block_size
    NAME                                 TYPE        VALUE
    db_block_size                        integer     8192
    SQL> show parameter cursor_sharing
    NAME                                 TYPE        VALUE
    cursor_sharing                       string      EXACT
    Trace:
    SQL> set autotrace traceonly arraysize 100
    SQL> SELECT
      2  *
      3  FROM
      4  M_UNDR M
      5  WHERE
      6  M.M_DATE = (SELECT MAX(M_DATE) FROM M_UNDR M1)
      7  AND
      8  M.M_TIME =
      9  (
    10  SELECT MAX(M_TIME) FROM M_UNDR M2 WHERE M2.M_DATE = M.M_DATE
    11  )
    12  AND
    13  M.U_TYPE NOT IN ('USD', 'GBP', 'EUR');
    239 rows selected.
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=19060 Card=1 Bytes
              =95)
       1    0   HASH JOIN (Cost=12882 Card=1 Bytes=95)
       2    1     VIEW OF 'VW_SQ_1' (VIEW) (Cost=6608 Card=508 Bytes=11176
       3    2       HASH (GROUP BY) (Cost=6608 Card=508 Bytes=10668)
       4    3         TABLE ACCESS (FULL) OF 'M_UNDR' (TABLE) (Cos
              t=6186 Card=2392724 Bytes=50247204)
       5    1     TABLE ACCESS (FULL) OF 'M_UNDR' (TABLE) (Cost=62
              74 Card=5594 Bytes=408362)
       6    5       SORT (AGGREGATE)
       7    6         TABLE ACCESS (FULL) OF 'M_UNDR' (TABLE) (Cos
              t=6178 Card=2392724 Bytes=19141792)
    Statistics
              1  recursive calls
              0  db block gets
          91479  consistent gets
           4830  physical reads
              0  redo size
          15457  bytes sent via SQL*Net to client
            359  bytes received via SQL*Net from client
              4  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
            239  rows processed
    SQL> disconnect
    SQL> select * from table(dbms_xplan.display_cursor(null, null, 'ALLSTATS LAST'));
    PLAN_TABLE_OUTPUT
    SQL_ID  0br4mzjgj63dw, child number 0
    SELECT /*+ gather_plan_statistics */ * FROM M_UNDR M WHERE M.M_DATE = (SELECT MAX(M_DATE) FROM
    M_UNDR M1) AND M.M_TIME = ( SELECT MAX(M_TIME) FROM M_UNDR M2 WHERE M2.M_DATE = M.M_DATE )
    AND M.U_TYPE NOT IN ('USD', 'GBP', 'EUR')
    Plan hash value: 1220141218
    | Id  | Operation            | Name           | Starts | E-Rows | A-Rows |   A-Time   | Buffers |  OMem |  1Mem | Used-Mem |
    |*  1 |  HASH JOIN           |                |      1 |      1 |    239 |00:00:06.94 |   91479 |  1114K|  1114K| 1209K (0)|
    |   2 |   VIEW               | VW_SQ_1        |      1 |    508 |    607 |00:00:04.06 |   30492 |    |  |          |
    |   3 |    HASH GROUP BY     |                |      1 |    508 |    607 |00:00:04.06 |   30492 |    |  |          |
    |   4 |     TABLE ACCESS FULL| M_UNDR |      1 |   2392K|   2695K|00:00:00.01 |   30492 |    |  |          |
    |*  5 |   TABLE ACCESS FULL  | M_UNDR |      1 |   5594 |   5497 |00:00:02.81 |   60987 |    |  |          |
    |   6 |    SORT AGGREGATE    |                |      1 |      1 |      1 |00:00:01.20 |   30492 |    |  |          |
    |   7 |     TABLE ACCESS FULL| M_UNDR |      1 |   2392K|   2695K|00:00:00.01 |   30492 |    |  |          |
    Predicate Information (identified by operation id):
       1 - access("M"."M_TIME"="VW_COL_1" AND "M_DATE"="M"."M_DATE")
       5 - filter(("M"."U_TYPE"<>'USD' AND "M"."U_TYPE"<>'GBP' AND "M"."U_TYPE"<>'EUR' AND "M"."M_DATE"=))
    26 rows selected.I have tried using rank as below. Didnt find any improvement.
    select * from
    SELECT
    m.*,
    rank() over (order by m_date desc, m_time desc) rnk
    FROM
    M_UNDR M
    WHERE
    M.U_TYPE NOT IN ('USD', 'GBP', 'EUR')
    where rnk  = 1Thanks in advance

    Hi,
    creating index on m_date and m_time did have gr8 impact on the plan.
    Query is completing in 2 sec now.
    Id  | Operation                      | Name               | Rows  | Bytes | Cost  |
       0 | SELECT STATEMENT               |                    |     1 |    73 |  6234 |
       1 |  TABLE ACCESS BY INDEX ROWID   | M_UNDR     |     2 |   146 |    51 |
       2 |   INDEX RANGE SCAN             | IND_M_UNDR |     2 |       |    49 |
       3 |    SORT AGGREGATE              |                    |     1 |    13 |       |
       4 |     FIRST ROW                  |                    |  5683 | 73879 |     6 |
       5 |      INDEX RANGE SCAN (MIN/MAX)| IND_M_UNDR |  5683 | 73879 |     6 |
       6 |    SORT AGGREGATE              |                    |     1 |     8 |       |
       7 |     INDEX FULL SCAN (MIN/MAX)  | IND_M_UNDR |  2392K|    18M|       |
    ------------------------------------------------------------------------------------Thanks for the help. Will check if there is any serious impact on insert.

  • How to tune the query..."sum" operation is taking too much long time...

    how to reduce the execution time for the below query..."sum" operation is taking too much long time....
    SELECT
    B.DP_AVPS_STATUS,
    SUM(DP_AD_CURR_BAL*D.ISIN_CLOSE_PRICE) Qty,
    B.DP_NET_WORTH,
    B.CMN_DP_FLAG,
    B.RESTRAIN_TYPE ,
    B.LETT_GENR_DATE,
    E.MAX_NET_WORTH,
    E.MIN_NET_WORTH
    FROM DPMADV0 A, PABRNCHDTLP0 B, PABANKCCYP0 D,PADPNETWORTHDTLP0 E,
    (SELECT CID_NUMB FROM CFCUSTMASTD0
    WHERE SUB_TYPE NOT IN (1,2,5,6,7,28,29,30,31,40,41,48,49,50,57,83)) C
    WHERE A.DP_AD_BR_NBR = B.BRNCH_NUMB
    AND A.DP_AD_CCY_CDE = D.CCY_ALPHA_CODE
    AND A.DP_AD_ACCT_NBR = C.CID_NUMB
    AND E.DP_ACCOUNT_TYPE = B.DP_ACCOUNT_TYPE
    AND SUBSTR(B.BRNCH_NUMB,1,3) like SUBSTR(:hvBrnchNumb,1,3)
    AND ((B.DP_TYPE IN (2) AND B.DP_ACCOUNT_TYPE IN (10, 11)) or
    (B.DP_TYPE IN (3) and B.DP_ACCOUNT_TYPE=11 ) )
    AND B.DEL_FLAG = 'N'
    AND B.DP_STATUS = 'A'
    AND D.ISIN_STATUS = 'A'
    GROUP BY B.DP_NET_WORTH,B.RESTRAIN_TYPE,B.DP_AVPS_STATUS,E.MAX_NET_WORTH,
    E.MIN_NET_WORTH,B.CMN_DP_FLAG,B.LETT_GENR_DATE;

    Hi,
    please produce a plan with rowsource statistics (if not sure how, follow instructions in http://savvinov.com/2012/09/24/a-sqlplus-script-for-diagnosing-poor-sql-plans/) and post it using tags to preserve formatting.
    Best regards,
      Nikolay
    P.S. I also suggest that you work on your open threads:
    Handle:      946903 
    Status Level:      Newbie
    Registered:      Jul 16, 2012
    Total Posts:      11
    Total Questions:      5 (5 unresolved)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to tune report query

    The below mentioned report query is taking too long time on my database.
    SELECT CALLINGPRTYNO ,CALLINGSUBSIMSI , CALLINGSUBSIMEI ,
    DECODE(CDRTYPE,'A0','TRANSIT','A1','MOC','A2','RCF','A3','FOW','A4','MTC','A5','SMO','A7','SMT')
    calltype,DTSTRTCHRG calldate,
    TMSTRTCHRG calltime, NVL(CHARGEDURN,0) callduration,CALLEDPRTYNO ,
    CALLEDSUBSIMSI ,CALLEDSUBSIMEI ,to_dec(substr(CELLIDFIRSTCELL,-4)) CELLIDFIRSTCELL,
    to_dec(substr(CELLIDLASTCELL,-4)) CELLIDLASTCELL, INCOMINGROUTE, OUTGOINGROUTE,MSCID FROM
    jk_VERIFICATION_0906 WHERE cdrtype IN ('A4','A7','A2') and SUBSTR(CALLEDPRTYNO,-10) = '9858073770'
    and DTSTRTCHRG >=to_date('01-06-09','dd-mm-yy') and DTSTRTCHRG <=to_date('10-06-09','dd-mm-yy');
    For performance tunning I have created local bitmap index on cdrtype column, local bitmap functional index SUBSTR("CALLINGPRTYNO",-10) cloumn and local functional index SUBSTR("CALLEDPRTYNO",-10) cloumn. The below is the explain plan for the query.......
    PLAN_TABLE_OUTPUT
    Plan hash value: 3944138671
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Pstart| Pstop |
    | 0 | SELECT STATEMENT | | 458K| 58M| 380K (1)| 01:31:40 | | |
    |* 1 | FILTER | | | | | | | |
    | 2 | PARTITION RANGE ITERATOR | | 458K| 58M| 380K (1)| 01:31:40 | KEY | KEY |
    |* 3 | TABLE ACCESS BY LOCAL INDEX ROWID| JK_VERIFICATION_0906 | 458K| 58M| 380K (1)| 01:31:40 | KEY | KEY |
    | 4 | BITMAP CONVERSION TO ROWIDS | | | | | | | |
    | 5 | BITMAP AND | | | | | | | |
    | 6 | BITMAP CONVERSION FROM ROWIDS | | | | | | | |
    |* 7 | INDEX RANGE SCAN | JK_IDX_CALLEDPRTY | 1031K| | 100 (39)| 00:00:02 | KEY | KEY |
    | 8 | BITMAP OR | | | | | | | |
    |* 9 | BITMAP INDEX SINGLE VALUE | JK_IDX_CDRTYPE | | | | | KEY | KEY |
    |* 10 | BITMAP INDEX SINGLE VALUE | JK_IDX_CDRTYPE | | | | | KEY | KEY |
    |* 11 | BITMAP INDEX SINGLE VALUE | JK_IDX_CDRTYPE | | | | | KEY | KEY |
    Predicate Information (identified by operation id):
    1 - filter(TO_DATE('01-06-09','dd-mm-yy')<=TO_DATE('10-06-09','dd-mm-yy'))
    3 - filter("DTSTRTCHRG"<=TO_DATE('10-06-09','dd-mm-yy') AND "DTSTRTCHRG">=TO_DATE('01-06-09','dd-mm-yy'))
    7 - access(SUBSTR("CALLEDPRTYNO",-10)='9858073770')
    9 - access("CDRTYPE"='A2')
    10 - access("CDRTYPE"='A4')
    11 - access("CDRTYPE"='A7')
    28 rows selected.
    But when I am executing the query on the database it is going for FULL TABLE SCAN instead of INDEX scan. Please let me know the reason why actual query execution is not picking the explain plan as giving by plan table output.
    Please let me know also if there is further tunning information is there to tune the above query.
    Thanks in Advance,
    Sukanta Paul.

    Formatting your SQL:
    SELECT CALLINGPRTYNO   ,
           CALLINGSUBSIMSI ,
           CALLINGSUBSIMEI ,
           DECODE(CDRTYPE,
                  'A0','TRANSIT',
                  'A1','MOC',
                  'A2','RCF',
                  'A3','FOW',
                  'A4','MTC',
                  'A5','SMO',
                  'A7','SMT')
                             calltype                        ,
           DTSTRTCHRG        calldate                        ,
           TMSTRTCHRG        calltime                        ,
           NVL(CHARGEDURN,0) callduration                    ,
           CALLEDPRTYNO                                      ,
           CALLEDSUBSIMSI                                    ,
           CALLEDSUBSIMEI                                    ,
           to_dec(SUBSTR(CELLIDFIRSTCELL,-4)) CELLIDFIRSTCELL,
           to_dec(SUBSTR(CELLIDLASTCELL,-4))  CELLIDLASTCELL ,
           INCOMINGROUTE                                     ,
           OUTGOINGROUTE                                     ,
           MSCID
    FROM   jk_VERIFICATION_0906
    WHERE  cdrtype IN ('A4',
                       'A7',
                       'A2')
       AND SUBSTR(CALLEDPRTYNO,-10) = '9858073770'
       AND DTSTRTCHRG              >=to_date('01-06-09','dd-mm-yy')
       AND DTSTRTCHRG              <=to_date('10-06-09','dd-mm-yy')Please enable 10046 trace before running the query and post the output from tkprof of the trace file.
    Follow this thread to learn the details [When your query takes too long|http://forums.oracle.com/forums/thread.jspa?threadID=501834]
    Also, is there any index on DTSTRTCHRG column ? Better post information about all the indexes on this table and when statistics were gathered last ?
    Please use { code } <your code here> { code } tags (without spaces around "code") to post SQL and tkprof output to retain the formatting.
    Regards,
    Amardeep Sidhu

  • Some Basic steps How to tune this Query

    Hi All
    This is my cursor Query to fetch the Eligible orders its taking too much of time to execute, This is my query
    SELECT oeol.header_id,oeol.attribute1,oeoh.order_number,COUNT(1) consignment_count
    FROM oe_order_lines_all oeol,oe_order_headers_all oeoh,oe_transaction_types_all oett
    WHERE oeol.header_id = oeoh.header_id
    AND oeol.flow_status_code IN(DECODE(oett.name,xxhdnl_om_common_util_pkg.g_push_line_type,
    DECODE(oeol.shipment_priority_code,'EXPRESS',DECODE(oeol.flow_status_code,'AWAITING_STOCK'
    ,'AWAITING_STOCK','STOCK_RECEIVED','STOCK_RECEIVED'),'STOCK_RECEIVED')
    ,DECODE(XXHDNL_OM_QUI_BAT_PLAN_EXT_PKG.check_push_or_pull(oeol.line_id),'PUSH','BOOKED')))
    AND(oeol.shipment_priority_code=p_shipment_priority OR p_shipment_priority IS NULL)
    AND oeol.line_type_id =oett.transaction_type_id AND oett.name IN
    (xxhdnl_om_common_util_pkg.g_return_line_type
    ,xxhdnl_om_common_util_pkg.g_push_line_type )
    AND oeoh.attribute3 IS NULL
    GROUP BY
    oeol.header_id
    ,oeol.attribute1
    ,oeoh.order_number;
    Pls provide some basic steps for tuning regarding some performance.
    thanks & regards
    Srikkanth.M

    Hi
    as I tried to say is that DECODE is just hard to read, but not a performance issue.
    What do you do in the XXHDNL_OM_QUI_BAT_PLAN_EXT_PKG.check_push_or_pull(oeol.line_id) procedure?
    But let me try the DECODE... not 100% correct as I can't test but you'll get the picture:
    SELECT
    FROM
    WHERE oeol.flow_status_code IN
    CASE WHEN oett.name = xxhdnl_om_common_util_pkg.g_push_line_type THEN
       CASE WHEN oeol.shipment_priority_code = 'EXPRESS' THEN
          CASE WHEN oeol.flow_status_code ='AWAITING_STOCK' THEN 'AWAITING_STOCK'
               WHEN oeol.flow_status_code ='STOCK_RECEIVED' THEN 'STOCK_RECEIVED'
               ELSE null END
          ELSE
          CASE WHEN XXHDNL_OM_QUI_BAT_PLAN_EXT_PKG.check_push_or_pull(oeol.line_id) = 'PUSH' THEN 'BOOKED'
             ELSE NULL END
    ELSE
    NULL
    ENDThat is a 1:1 "translation" PLEASE add comments in nested statements.
    And this is easier to read, as in CASE you can use AND / OR / IN ....
    SELECT
    FROM
    WHERE oeol.flow_status_code IN
    CASE WHEN oett.name = xxhdnl_om_common_util_pkg.g_push_line_type THEN
       CASE WHEN oeol.shipment_priority_code = 'EXPRESS' AND oeol.flow_status_code IN ('AWAITING_STOCK','STOCK_RECEIVED')
         THEN oeol.flow_status_code ELSE NULL END
       ELSE
        CASE WHEN XXHDNL_OM_QUI_BAT_PLAN_EXT_PKG.check_push_or_pull(oeol.line_id) = 'PUSH' THEN 'BOOKED'
             ELSE NULL END
    ENDThe "oeol.flow_status_code IN" makes no sense as the output of/DECODE/CASE is always 1 value right? And I would use the logic on a select on table "oe_order_lines_all" and then use the calculated field as a JOIN criteria. Much easier to test and read.
    But, please check the procedure which you call that can be deadly! The "case" is just "nice to have"
    -- andy

  • Hi.how to tune this query?

    select *
    from exp_final
    where
    to_number(to_char(process_date,'mm'))=to_number(to_char(sysdate,'mm'))-1

    Both Sven's and theoa's suggestions are fundamentally different from the query OP referred to originally.
    It maybe that the original query is completely wrong (that would be my instinct too).
    Original query:
    select *
    from exp_final
    where
    to_number(to_char(process_date,'mm'))=to_number(to_char(sysdate,'mm'))-1 implies that you want everything from exp_final where the process_date was in the same month as the current month -1, regardless of year. For example, run today this will bring back everything done in a December, whether it was December 1972, December 1815 or December 2010.
    Whereas their suggestions rely on your query being wrong and what you really want to get is everything from last month - i.e. run today, fetch everything from December 2010.
    Which is the correct requirement?

  • Tune hierarchy query

    Hi,
    I have a table which holds geographical data in a hierrachical format. I need to retriev all the parent-information in a single query.
    The table is called CX_GEO_DATA, which stores hierrarchy relations .
    eg of data
    row_id type name parent_id start_dt end_dt
    1 Zip 400 2 1/2/2009 1/1/2020
    2 City San
    I need to extract all the parent information from the table, i.e. given a row_id, find its parents.
    Since it is a part of UI requiremnt a performence of 5 secs is desired.
    SELECT A.type,
         a.name,
              A.ALT_NAME,
              LEVEL,
                   a.start_dt,
                   a.end_dt,
                   a.par_geo_data_id,
              a.row_id
              FROM cx_geo_data A
    WHERE TRUNC(SYSDATE) BETWEEN START_DT AND NVL(END_DT,SYSDATE+1)
                   START WITH row_id = :p_row_id
    CONNECT BY PRIOR par_geo_data_id = row_id
    There are indexes in table on columns:
    Non unique par_geo_data_id
    Non unique name
    Unique Row_id (Primary key)
    I need result in the below form:
    i.e. given a row_id find all the parents for that record.
    Say if I get a Zip, get all its parents, i.e. Country, state, City, Zip etc
    To achieve that I have written a function:
    Which uses the query listed on top. i.e. a connect by query and returns a given type of parent.
    Below is the function code:
    FUNCTION get_par_at_a_level_info
    p_row_id varchar2,
    p_type_of_Parent varchar2
    RETURN VARCHAR2
    IS
    vParent_Name cx_geo_data.alt_name%type;
    BEGIN
    SELECT alt_name
    INTO vParent_Name
    FROM (
    SELECT A.type,
         a.name,
              A.ALT_NAME,
              LEVEL,
              a.row_id
              FROM cx_geo_data A
    WHERE TRUNC(SYSDATE) BETWEEN START_DT AND NVL(END_DT,SYSDATE+1)
    START WITH row_id = p_row_id
    CONNECT BY PRIOR par_geo_data_id = row_id
    )hier_tab
    WHERE hier_tab.type=p_type_of_Parent;
    return(initCap(vParent_Name));
    EXCEPTION
    WHEN no_data_found
    THEN RETURN NULL;
    WHEN OTHERS
    THEN RAISE;
    END get_par_at_a_level_info;
    So, if I need type of parent as Country I pass country to it, if I need City I pass City to the function.
    So, my final query is like:
    SELECT GEO_TYPE,
    GEO_NAME,
         geoElementId GEO_ELEMENT_ID,
              xxfdev_geo_bndary_pkg.Get_Par_at_a_level_info(geoElementId,'Country') COUNTRY,
         xxfdev_geo_bndary_pkg.Get_Par_at_a_level_info(geoElementId,'State') STATE,
         ---     xxfdev_geo_bndary_pkg.Get_Par_at_a_level_info(geoElementId,'City') CITY,
         xxfdev_geo_bndary_pkg.Get_Par_at_a_level_info(geoElementId,'Zip') ZIP
         FROM ( SELECT
         ---------restirction by user ideally nt reqd
         terr_gb.name NAME,
    INITCAP(geo.alt_name) GEO_NAME,
         geo.geoElementId,
         geo.TYPE GEO_TYPE,
         from cx_geo_data
    where row_id=p_row_id
    );

    let me know on how to tune this query or if there is any option to re-write it in any other form.

  • Guide me to tune the query

    Hi All,
    I need to tune the query which is taking more than 1 hour to execute over 8 Lakhs of record.
    SQL> explain plan for SELECT C.aci_cust_code      cust_code,
    2 C.aci_cust_name cust_name,
    3      R.NAME ruledefination,
    4 B.RULECODE ALERTS,
    5 A.custom1 tran_id,
    6 TD_get_value('AMLTRANTYPE', RTRIM(A.custom17)) trantype,
    7 A.CUSTOM18 tran_nature,
    8 A.custom25 tran_date,
    9 A.messageno messageno,
    10 TD_get_value('AMLTRANSTATUS', A.status) msgstatus,
    11 D.acai_acct_type acct_type,
    12 A.custom19 acct_number,
    13 A.CURRENCY CURRENCY,
    14 A.priorityamount amount,
    15 A.operator USERNAME,
    16 A.msgdb_id msgdb_id,
    17 A.msg_mode_in msg_mode_in
    18 FROM MSGDB A,
    19 MSGALERTS B,
    20 AML_CUST_INFO C,
    21      AML_CUST_ACC_INFO D,
    22 RULETBL2 R,
    23           (SELECT tdkey FROM tabledetails WHERE tdidcode = 'AML-INCLUDEQ' ) amlqueues
    24 WHERE A.msgdb_id = B.msgdb_id AND
    25 A.queueid = amlqueues.tdkey AND
    26           A.MSG_MODE_IN = 'AML-TRANS' AND
    27 A.custom15 = C.aci_cust_code AND
    28 A.CUSTOM19=D.ACAI_ACCT_NUMBER(+) AND
    29 TO_CHAR(A.custom25,'YYYYMMDD') BETWEEN
    30      TO_CHAR(TO_DATE('2011/01/01','YYYY/MM/DD'),'YYYYMMDD')
    31 AND TO_CHAR(TO_DATE('2011/01/31','YYYY/MM/DD'),'YYYYMMDD')
    32 AND B.RULECODE = R.RULECODE
    33 ORDER BY A.custom25, msgdb_id,B.rulecode;
    Explained.
    PLAN_TABLE_OUTPUT
    Plan hash value: 1081661146
    | Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 173K| 30M| | 12697 (2)| 00:02:33 |
    | 1 | SORT ORDER BY | | 173K| 30M| 66M| 12697 (2)| 00:02:33 |
    |* 2 | HASH JOIN | | 173K| 30M| | 5580 (4)| 00:01:07 |
    | 3 | VIEW | index$_join$_005 | 3395 | 81480 | | 42 (3)| 00:00:01 |
    |* 4 | HASH JOIN | | | | | | |
    | 5 | INDEX FAST FULL SCAN | IDX_RCODE | 3395 | 81480 | | 10 (0)| 00:00:01 |
    | 6 | INDEX FAST FULL SCAN | SYS_C0040836 | 3395 | 81480 | | 31 (0)| 00:00:01 |
    |* 7 | HASH JOIN | | 1737 | 276K| | 5534 (4)| 00:01:07 |
    |* 8 | HASH JOIN | | 559 | 86645 | | 4575 (3)| 00:00:55 |
    |* 9 | HASH JOIN OUTER | | 448 | 56000 | | 4463 (3)| 00:00:54 |
    | 10 | NESTED LOOPS | | 448 | 47040 | | 4404 (3)| 00:00:53 |
    |* 11 | TABLE ACCESS BY INDEX ROWID| MSGDB | 451 | 35178 | | 4403 (3)| 00:00:53 |
    |* 12 | INDEX RANGE SCAN | I_MODEDATE | 2292 | | | 4323 (3)| 00:00:52 |
    |* 13 | INDEX UNIQUE SCAN | PK_TABLEDETAIL | 1 | 27 | | 0 (0)| 00:00:01 |
    | 14 | INDEX FAST FULL SCAN | ACC_NUMBER_TYPE | 58947 | 1151K| | 58 (4)| 00:00:01 |
    | 15 | TABLE ACCESS FULL | AML_CUST_INFO | 18340 | 537K| | 111 (1)| 00:00:02 |
    | 16 | TABLE ACCESS FULL | MSGALERTS | 868K| 6782K| | 944 (4)| 00:00:12 |
    There is no index on RULECODE of MSGALERTS and RULETBL2 table.
    Could yu guys guide me how to tune this query with or without creating any new index.
    Thanks,

    To emphasise what hoek has said regarding dates, NEVER compare dates with dates by converting them to strings (or numbers). By doing so, you remove vital information from the optimizer.
    For example, what is the difference between "31st Dec 2010" and "1st Jan 2011"? Easy, they're dates, that's 1 day.
    But what's the difference between "20101231" and "20110101"? Easy: 20110101 - 20101231 = 8870.
    That makes the difference between the optimizer guessing 1 row or 8870 rows... a fairly big difference, I think you'll agree, which could well impact on the plan the optimizer chooses.
    One other point - leaving the clause as dates gives:
    AND    a.custom25 BETWEEN TO_DATE('2011/01/01', 'YYYY/MM/DD')
                          AND TO_DATE('2011/01/31', 'YYYY/MM/DD') which excludes any dates on 31st Jan 2011 except midnight, eg. 10am on 31st Jan 2011 won't be returned by your query.
    If you're after rows for a given month, then you could do:
    AND    trunc(a.custom25, 'mm') = TO_DATE('01/01/2011', 'dd/mm/yyyy')

Maybe you are looking for