SQL query performance question

So I had this long query that looked like this:
SELECT a.BEGIN_DATE, a.END_DATE, a.DEAL_KEY, (select name from ideal dd where a.deal_key = dd.deal_key) DEALNAME, a.deal_term_key
FROM
ideal d, ideal_term a,( select deal_key, deal_term_key, max(createdOn) maxdate    from Ideal_term B
where createdOn <= '03-OCT-12 10.03.00 AM' group by deal_key, deal_term_key ) B
WHERE  a.begin_date <= '20-MAR-09 01.01.00 AM'
*     and a.end_date >= '19-MAR-09 01.00.00 AM'*
*     and A.deal_key = b.deal_key*
*     and A.deal_term_key = b.deal_term_key*
*     and     a.createdOn = b.maxdate*
*     and d.deal_key = a.deal_key*
*     and d.name like 'MVPP1 B'*
order by
*     a.begin_date, a.deal_key, a.deal_term_key;*
This performed very poorly for a record in one of the tables that has 43,000+ revisions. It took about 1 minute and 40 seconds. I asked the database guy at my company for help with it and he re-wrote it like so:
SELECT a.BEGIN_DATE, a.END_DATE, a.DEAL_KEY, (select name from ideal dd where a.deal_key = dd.deal_key) DEALNAME, a.deal_term_key
FROM ideal d
INNER JOIN (SELECT deal_key,
deal_term_key,
MAX(createdOn) maxdate
FROM Ideal_term B2
WHERE '03-OCT-12 10.03.00 AM' >= createdOn
GROUP BY deal_key, deal_term_key) B1
ON d.deal_key = B1.deal_key
INNER JOIN ideal_term a
ON B1.deal_key = A.deal_key
AND B1.deal_term_key = A.deal_term_key
AND B1.maxdate = a.createdOn
AND d.deal_key = a.deal_key + 0
WHERE a.begin_date <= '20-MAR-09 01.01.00 AM'
AND a.end_date >= '19-MAR-09 01.00.00 AM'
AND d.name LIKE 'MVPP1 B'
ORDER BY a.begin_date, a.deal_key, a.deal_term_key
this works much better, it only takes 0.13 seconds. I've bee trying to figure out why exaclty his version performs so much better. His only epxlanation was that the "+ 0" in the WHERE clause prevented Oracle from using an index for that column which created a bad plan initially.
I think there has to be more to it than that though. Can someone give me a detailed explanation of why the second version of the query performed so much faster.
Thanks.
Edited by: su**** on Oct 10, 2012 1:31 PM

I used Autotrace in SQL developer. Is that sufficient? Here is the Autotrace and Explain for the slow query:
and for the fast query:
I said that I thought there was more to it because when my team members and I looked at the re-worked query the database guy sent us, our initial thoughts were that in the slow query some of the tables didn't have joins and because of that the query formed a Cartesian product and this resulted in a huge 43,000+ rows matrix.
In his version all tables had joins properly defined and in addition he had that +0 which told it to ignore the index for the attribute deal_key of table ideal_term. I spoke with the database guy today and he confirmed our theory.

Similar Messages

  • SQL query performance issues.

    Hi All,
    I worked on the query a month ago and the fix worked for me in test intance but failed in production. Following is the URL for the previous thread.
    SQL query performance issues.
    Following is the tkprof file.
    CURSOR_ID:76  LENGTH:2383  ADDRESS:f6b40ab0  HASH_VALUE:2459471753  OPTIMIZER_GOAL:ALL_ROWS  USER_ID:443 (APPS)
    insert into cos_temp(
    TRX_DATE, DEPT, PRODUCT_LINE, PART_NUMBER,
    CUSTOMER_NUMBER, QUANTITY_SOLD, ORDER_NUMBER,
    INVOICE_NUMBER, EXT_SALES, EXT_COS,
    GROSS_PROFIT, ACCT_DATE,
    SHIPMENT_TYPE,
    FROM_ORGANIZATION_ID,
    FROM_ORGANIZATION_CODE)
    select a.trx_date,
    g.segment5 dept,
    g.segment4 prd,
    m.segment1 part,
    d.customer_number customer,
    b.quantity_invoiced units,
    --       substr(a.sales_order,1,6) order#,
    substr(ltrim(b.interface_line_attribute1),1,10) order#,
    a.trx_number invoice,
    (b.quantity_invoiced * b.unit_selling_price) sales,
    (b.quantity_invoiced * nvl(price.operand,0)) cos,
    (b.quantity_invoiced * b.unit_selling_price) -
    (b.quantity_invoiced * nvl(price.operand,0)) profit,
    to_char(to_date('2010/02/28 00:00:00','yyyy/mm/dd HH24:MI:SS'),'DD-MON-RR') acct_date,
    'DRP',
    l.ship_from_org_id,
    p.organization_code
    from   ra_customers d,
    gl_code_combinations g,
    mtl_system_items m,
    ra_cust_trx_line_gl_dist c,
    ra_customer_trx_lines b,
    ra_customer_trx_all a,
    apps.oe_order_lines l,
    apps.HR_ORGANIZATION_INFORMATION i,
    apps.MTL_INTERCOMPANY_PARAMETERS inter,
    apps.HZ_CUST_SITE_USES_ALL site,
    apps.qp_list_lines_v price,
    apps.mtl_parameters p
    where a.trx_date between to_date('2010/02/01 00:00:00','yyyy/mm/dd HH24:MI:SS')
    and to_date('2010/02/28 00:00:00','yyyy/mm/dd HH24:MI:SS')+0.9999
    and   a.batch_source_id = 1001     -- Sales order shipped other OU
    and   a.complete_flag = 'Y'
    and   a.customer_trx_id = b.customer_trx_id
    and   b.customer_trx_line_id = c.customer_trx_line_id
    and   a.sold_to_customer_id = d.customer_id
    and   b.inventory_item_id = m.inventory_item_id
    and   m.organization_id
         = decode(substr(g.segment4,1,2),'01',5004,'03',5004,
         '02',5003,'00',5001,5002)
    and   nvl(m.item_type,'0') <> '111'
    and   c.code_combination_id = g.code_combination_id+0
    and   l.line_id = b.interface_line_attribute6
    and   i.organization_id = l.ship_from_org_id
    and   p.organization_id = l.ship_from_org_id
    and   i.org_information3 <> '5108'
    and   inter.ship_organization_id = i.org_information3
    and   inter.sell_organization_id = '5108'
    and   inter.customer_site_id = site.site_use_id
    and   site.price_list_id = price.list_header_id
    and   product_attr_value = to_char(m.inventory_item_id)
    call        count       cpu   elapsed         disk        query      current         rows    misses
    Parse           1      0.47      0.56           11          197            0            0         1
    Execute         1   3733.40   3739.40        34893    519962154           11          188         0
    total           2   3733.87   3739.97        34904    519962351           11          188         1
    |         Rows Row Source Operation
    | ------------ ---------------------------------------------------
    |          188 HASH JOIN (cr=519962149 pr=34889 pw=0 time=2607.35)
    |          741 .TABLE ACCESS BY INDEX ROWID QP_PRICING_ATTRIBUTES (cr=519939426 pr=34889 pw=0 time=2457.32)
    |    254644500 ..NESTED LOOPS (cr=519939265 pr=34777 pw=0 time=3819.67)
    |    254643758 ...NESTED LOOPS (cr=8921833 pr=29939 pw=0 time=1274.41)
    |          741 ....NESTED LOOPS (cr=50042 pr=7230 pw=0 time=11.37)
    |          741 .....NESTED LOOPS (cr=48558 pr=7229 pw=0 time=11.35)
    |          741 ......NESTED LOOPS (cr=47815 pr=7223 pw=0 time=11.32)
    |         3237 .......NESTED LOOPS (cr=41339 pr=7223 pw=0 time=12.42)
    |         3237 ........NESTED LOOPS (cr=38100 pr=7223 pw=0 time=12.39)
    |         3237 .........NESTED LOOPS (cr=28296 pr=7139 pw=0 time=12.29)
    |         1027 ..........NESTED LOOPS (cr=17656 pr=4471 pw=0 time=3.81)
    |         1027 ...........NESTED LOOPS (cr=13537 pr=4404 pw=0 time=3.30)
    |          486 ............NESTED LOOPS (cr=10873 pr=4240 pw=0 time=0.04)
    |          486 .............NESTED LOOPS (cr=10385 pr=4240 pw=0 time=0.03)
    |          486 ..............TABLE ACCESS BY INDEX ROWID RA_CUSTOMER_TRX_ALL (cr=9411 pr=4240 pw=0 time=0.02)
    |        75253 ...............INDEX RANGE SCAN RA_CUSTOMER_TRX_N5 (cr=403 pr=285 pw=0 time=0.38)
    |          486 ..............TABLE ACCESS BY INDEX ROWID HZ_CUST_ACCOUNTS (cr=974 pr=0 pw=0 time=0.01)
    |          486 ...............INDEX UNIQUE SCAN HZ_CUST_ACCOUNTS_U1 (cr=488 pr=0 pw=0 time=0.01)
    |          486 .............INDEX UNIQUE SCAN HZ_PARTIES_U1 (cr=488 pr=0 pw=0 time=0.01)
    |         1027 ............TABLE ACCESS BY INDEX ROWID RA_CUSTOMER_TRX_LINES_ALL (cr=2664 pr=164 pw=0 time=1.95)
    |         2063 .............INDEX RANGE SCAN RA_CUSTOMER_TRX_LINES_N2 (cr=1474 pr=28 pw=0 time=0.22)
    |         1027 ...........TABLE ACCESS BY INDEX ROWID RA_CUST_TRX_LINE_GL_DIST_ALL (cr=4119 pr=67 pw=0 time=0.54)
    |         1027 ............INDEX RANGE SCAN RA_CUST_TRX_LINE_GL_DIST_N1 (cr=3092 pr=31 pw=0 time=0.20)
    |         3237 ..........TABLE ACCESS BY INDEX ROWID MTL_SYSTEM_ITEMS_B (cr=10640 pr=2668 pw=0 time=15.35)
    |         3237 ...........INDEX RANGE SCAN MTL_SYSTEM_ITEMS_B_U1 (cr=2062 pr=40 pw=0 time=0.33)
    |         3237 .........TABLE ACCESS BY INDEX ROWID OE_ORDER_LINES_ALL (cr=9804 pr=84 pw=0 time=0.77)
    |         3237 ..........INDEX UNIQUE SCAN OE_ORDER_LINES_U1 (cr=6476 pr=47 pw=0 time=0.43)
    |         3237 ........TABLE ACCESS BY INDEX ROWID MTL_PARAMETERS (cr=3239 pr=0 pw=0 time=0.04)
    |         3237 .........INDEX UNIQUE SCAN MTL_PARAMETERS_U1 (cr=2 pr=0 pw=0 time=0.01)
    |          741 .......TABLE ACCESS BY INDEX ROWID HR_ORGANIZATION_INFORMATION (cr=6476 pr=0 pw=0 time=0.10)
    |         6474 ........INDEX RANGE SCAN HR_ORGANIZATION_INFORMATIO_FK2 (cr=3239 pr=0 pw=0 time=0.03)Please help.
    Regards
    Ashish

    |    254644500 ..NESTED LOOPS (cr=519939265 pr=34777 pw=0 time=3819.67)
    |    254643758 ...NESTED LOOPS (cr=8921833 pr=29939 pw=0 time=1274.41)There is no way the optimizer should choose to process that many rows using nested loops.
    Either the statistics are not up to date, the data values are skewed or you have some optimizer parameter set to none default to force index access.
    Please post explain plan and optimizer* parameter settings.

  • How does Index fragmentation and statistics affect the sql query performance

    Hi,
    How does Index fragmentation and statistics affect the sql query performance
    Thanks
    Shashikala
    Shashikala

    How does Index fragmentation and statistics affect the sql query performance
    Very simple answer, outdated statistics will lead optimizer to create bad plans which in turn will require more resources and this will impact performance. If index is fragmented ( mainly clustered index,holds true for Non clustred as well) time spent in finding
    the value will be more as query would have to search fragmented index to look for data, additional spaces will increase search time.
    Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers
    My TechNet Wiki Articles

  • SQL Query Performance needed.

    Hi All,
       I am getting performance issue with my below sql query. When I fired it, It is taking 823.438 seconds, but when I ran query in, it is taking 8.578 seconds, and query after in   is taking 7.579 seconds.
    SELECT BAL.L_ID, BAL.L_TYPE, BAL.L_NAME, BAL.NATURAL_ACCOUNT,
     BAL.LOCATION, BAL.PRODUCT, BAL.INTERCOMPANY, BAL.FUTURE1, BAL.FUTURE2, BAL.CURRENCY, BAL.AMOUNT_PTD, BAL.AMOUNT_YTD, BAL.CREATION_DATE,
     BAL.CREATED_BY, BAL.LAST_UPDATE_DATE, BAL.LAST_UPDATED_BY, BAL.STATUS, BAL.ANET_STATUS, BAL.COG_STATUS, BAL.comb_id, BAL.MESSAGE,
     SEG.SEGMENT_DESCRIPTION  FROM ACC_SEGMENTS_V_TST SEG , ACC_BALANCE_STG BAL where BAL.NATURAL_ACCOUNT = SEG.SEGMENT_VALUE AND SEG.SEGMENT_COLUMN = 'SEGMENT99' AND BAL.ACCOUNTING_PERIOD = 'MAY-10' and BAL.comb_id
    in  
    (select comb_id from
     (select comb_id, rownum r from
      (select distinct(comb_id),LAST_UPDATE_DATE from ACC_BALANCE_STG where accounting_period='MAY-10' order by LAST_UPDATE_DATE )    
         where rownum <=100)  where r >0)
    Please help me in fine tuning above. I am using Oracle 10g database. There are total of 8000 records. Let me know if any other info required.
    Thanks in advance.

    In recent versions of Oracle an EXISTS predicate should produce the same execution plan as the corresponding IN clause.
    Follow the advice in the tuning threads as suggested by SomeoneElse.
    It looks to me like you could avoid the double pass on ACC_BALANCE_STG by using an analytical function like ROW_NUMBER() and then joining to ACC_SEGMENTS_V_TST SEG, maybe using subquery refactoring to make it look nicer.
    e.g. something like (untested)
    WITH subq_bal as
        ((SELECT *
          FROM (SELECT BAL.L_ID, BAL.L_TYPE, BAL.L_NAME, BAL.NATURAL_ACCOUNT,
                 BAL.LOCATION, BAL.PRODUCT, BAL.INTERCOMPANY, BAL.FUTURE1, BAL.FUTURE2,
                 BAL.CURRENCY, BAL.AMOUNT_PTD, BAL.AMOUNT_YTD, BAL.CREATION_DATE,
                 BAL.CREATED_BY, BAL.LAST_UPDATE_DATE, BAL.LAST_UPDATED_BY, BAL.STATUS, BAL.ANET_STATUS,
                 BAL.COG_STATUS, BAL.comb_id, BAL.MESSAGE,
                 ROW_NUMBER() OVER (ORDER BY LAST_UPDATE_DATE) rn
                 FROM   acc_balance_stg
                 WHERE  accounting_period='MAY-10')
          WHERE rn <= 100)
    SELECT *
    FROM   subq_bal bal
    ,      acc_Segments_v_tst seg
    where  BAL.NATURAL_ACCOUNT = SEG.SEGMENT_VALUE
    AND    SEG.SEGMENT_COLUMN = 'SEGMENT99';However, the parentheses you use around comb_id make me question what your intention is here in the subquery?
    Do you have multiple rows in ACC_BALANCE_STG for the same comb_id and last_update_date?
    If so you may want to do a MAX on last_update_date, group by comb_id before doing the analytic restriction.
    Edited by: DomBrooks on Jun 16, 2010 5:56 PM

  • SQL Query Performance

    Hi There,
    We have a sql query that runs between 2 databases on the same machine, the sql takes about 2 mins and returns about 6400 rows. When the process started running we used to see results in about 13 secs, now it's taking almost 2 mins for the same data set. We have updated the stats (table and index) but to no use. I've been trying to get the execution plan to see if there is anything abnormal going on but as the core of the sql is done remotely, we haven't been able to get much out of it.
    Here is the sql:
    SELECT  
    --/*+ DRIVING_SITE(var) ALL_ROWS */
             ventity_id, ar_action_performed, action_date,
             'ventity_ar' ar_tab
        FROM (SELECT var.ventity_id, var.ar_action_performed, var.action_date,
                     var.familyname_id, var.status, var.isprotected,
                     var.dateofbirth, var.gender, var.sindigits,
                     LAG (var.familyname_id) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                lag_familyname_id,
                     LAG (var.status) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                       lag_status,
                     LAG (var.isprotected) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                  lag_isprotected,
                     LAG (var.dateofbirth) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                  lag_dateofbirth,
                     LAG (var.gender) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                       lag_gender,
                     LAG (var.sindigits) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                    lag_sindigits
                FROM cpp_schema.ventity_ar@CdpP var,
                     -- reduce the set to ventity_id that had a change within the time frame,
                     -- and filter out RETRIEVEs as they do not signal change
                     (SELECT DISTINCT ventity_id
                                 FROM cpp_schema.ventity_ar@CdpP
                                WHERE action_date BETWEEN '01-MAR-10' AND '10-APR-10'
                                  AND ar_action_performed <> 'RTRV') m
               WHERE var.action_date <= '10-APR-10'
                 AND var.ventity_id = m.ventity_id
                 AND var.ar_action_performed <> 'RTRV') mm
       WHERE action_date BETWEEN '01-MAR-10' AND '10-APR-10'
         -- most of the columns from the data table allow nulls
         AND (   (NVL (familyname_id, 0) <> NVL (lag_familyname_id, 0))
              OR (NVL (status, 'x') <> NVL (lag_status, 'x'))
              OR (NVL (isprotected, 2) <> NVL (lag_isprotected, 2))
              OR (NVL (dateofbirth, TO_DATE ('15000101', 'yyyymmdd')) <>
                           NVL (lag_dateofbirth, TO_DATE ('15000101', 'yyyymmdd'))
              OR (NVL (gender, 'x') <> NVL (lag_gender, 'x'))
              OR (NVL (sindigits, 'x') <> NVL (lag_sindigits, 'x'))
    ORDER BY ventity_id, action_date DESC
    6401 rows selected.
    Elapsed: 00:01:47.03
    Execution Plan
    Plan hash value: 3953446945
    | Id  | Operation        | Name | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     | Inst   |IN-OUT|
    |   0 | SELECT STATEMENT |      |    12M|  1575M|       |   661K  (1)| 02:12:22 |        |      |
    |   1 |  SORT ORDER BY   |      |    12M|  1575M|  2041M|   661K  (1)| 02:12:22 |        |      |
    |*  2 |   VIEW           |      |    12M|  1575M|       |   291K  (2)| 00:58:13 |        |      |
    |   3 |    REMOTE        |      |       |       |       |            |          | CCP01  | R->S |
       2 - filter("action_date">='01_MAR-10' AND "action_date"<='10-APR-10' AND
                  (NVL("FAMILYNAME_id",0)<>NVL("LAG_FAMILYNAME_id",0) OR
                  NVL("STATUS",'x')<>NVL("LAG_STATUS",'x') OR NVL("ISPROTECTED",2)<>NVL("LAG_ISPROTECTED",2
                  ) OR NVL("DATEOFBIRTH",TO_DATE(' 1500-01-01 00:00:00', 'syyyy-mm-dd
                  hh24:mi:ss'))<>NVL("LAG_DATEOFBIRTH",TO_DATE(' 1500-01-01 00:00:00', 'syyyy-mm-dd
                  hh24:mi:ss')) OR NVL("GENDER",'x')<>NVL("LAG_GENDER",'x') OR
                  NVL("SINDIGITS",'x')<>NVL("LAG_SINDIGITS",'x')))
    Remote SQL Information (identified by operation id):
       3 - EXPLAIN PLAN SET STATEMENT_ID='PLUS4294967295' INTO PLAN_TABLE@! FOR SELECT
           "A2"."ventity_id","A2"."AR_ACTION_PERFORMED","A2"."action_date","A2"."FAMILYNAME_id","A2"
           ."STATUS","A2"."ISPROTECTED","A2"."DATEOFBIRTH","A2"."GENDER","A2"."SINDIGITS",DECODE(COU
           NT(*) OVER ( PARTITION BY "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS  BETWEEN 1
           PRECEDING  AND 1 PRECEDING ),1,FIRST_VALUE("A2"."FAMILYNAME_id") OVER ( PARTITION BY
           "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS  BETWEEN 1 PRECEDING  AND 1 PRECEDING
           ),NULL),DECODE(COUNT(*) OVER ( PARTITION BY "A2"."ventity_id" ORDER BY
           "A2"."action_date" ROWS  BETWEEN 1 PRECEDING  AND 1 PRECEDING ),1,FIRST_VALUE("A2"."STATUS")
           OVER ( PARTITION BY "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS  BETWEEN 1
           PRECEDING  AND 1 PRECEDING ),NULL),DECODE(COUNT(*) OVER ( PARTITION BY
           "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS  BETWEEN 1 PRECEDING  AND 1 PRECEDING
           ),1,FIRST_VALUE("A2"."ISPROTECTED") OVER ( PARTITION BY "A2"."ventity_id" ORDER BY
           "A2"."action_date" ROWS  BETWEEN 1 PRECEDING  AND 1 PRECEDING ),NULL),DECODE(COUNT(*) OVER (
           PARTITION BY "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS  BETWEEN 1 PRECEDING
           AND 1 PRECEDING ),1,FIRST_VALUE("A2"."DATEOFBIRTH") OVER ( PARTITION BY
           "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS  BETWEEN 1 PRECEDING  AND 1 PRECEDING
           ),NULL),DECODE(COUNT(*) OVER ( PARTITION BY "A2"."ventity_id" ORDER BY
           "A2"."action_date" ROWS  BETWEEN 1 PRECEDING  AND 1 PRECEDING ),1,FIRST_VALUE("A2"."GENDER")
           OVER ( PARTITION BY "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS  BETWEEN 1
           PRECEDING  AND 1 PRECEDING ),NULL),DECODE(COUNT(*) OVER ( PARTITION BY
           "A2"."ventity_id" ORDER BY "A2"."action_date" ROWS  BETWEEN 1 PRECEDING  AND 1 PRECEDING
           ),1,FIRST_VALUE("A2"."SINDIGITS") OVER ( PARTITION BY "A2"."ventity_id" ORDER BY
           "A2"."action_date" ROWS  BETWEEN 1 PRECEDING  AND 1 PRECEDING ),NULL) FROM
           "CPP_SCHEMA"."ventity_AR" "A2", (SELECT DISTINCT "A3"."ventity_id"
           "ventity_id" FROM "CPP_SCHEMA"."ventity_AR" "A3" WHERE
           "A3"."action_date">='01_MAR-10' AND "A3"."action_date"<='10-APR-10' AND
           "A3"."AR_ACTION_PERFORMED"<>'RETRIEVE' AND TO_DATE('01_MAR-10')<=TO_DATE('10-APR-10'))
           "A1" WHERE "A2"."action_date"<='10-APR-10' AND "A2"."ventity_id"="A1"."ventity_id"
           AND "A2"."AR_ACTION_PERFORMED"<>'RETRIEVE' (accessing 'EBCP01.EBC.GOV.BC.CA' )Your advise and/or help is highly appreciated.
    THanks
    Edited by: rsar001 on Apr 20, 2010 6:57 AM

    Maybe I'm missing something but this subquery seems inefficient:
    SELECT var.ventity_id, var.ar_action_performed, var.action_date,
                     var.familyname_id, var.status, var.isprotected,
                     var.dateofbirth, var.gender, var.sindigits,
                     LAG (var.familyname_id) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                lag_familyname_id,
                     LAG (var.status) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                       lag_status,
                     LAG (var.isprotected) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                  lag_isprotected,
                     LAG (var.dateofbirth) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                  lag_dateofbirth,
                     LAG (var.gender) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                       lag_gender,
                     LAG (var.sindigits) OVER (PARTITION BY var.ventity_id ORDER BY action_date)
                                                                    lag_sindigits
                FROM cpp_schema.ventity_ar@CdpP var,
                     -- reduce the set to ventity_id that had a change within the time frame,
                     -- and filter out RETRIEVEs as they do not signal change
                     (SELECT DISTINCT ventity_id
                                 FROM cpp_schema.ventity_ar@CdpP
                                WHERE action_date BETWEEN '01-MAR-10' AND '10-APR-10'
                                  AND ar_action_performed <> 'RTRV') m
               WHERE var.action_date <= '10-APR-10'
                 AND var.ventity_id = m.ventity_id
                 AND var.ar_action_performed != 'RTRV'I don't think accessing the VENTITY_AR table twice is helping you here. The comments looks like you want to restrict the set of VENTITY_IDs but if you look at the plan it is not happening. The plan is reading them from the index and joining against the full VENTITY_AR table anyways. I recommend you consolidate it into something like this:
    SELECT  var.ventity_id
    ,       var.ar_action_performed
    ,       var.action_date
    ,       var.familyname_id
    ,       var.status
    ,       var.isprotected
    ,       var.dateofbirth
    ,       var.gender
    ,       var.sindigits
    ,       LAG (var.familyname_id) OVER (PARTITION BY var.ventity_id ORDER BY action_date)         AS lag_familyname_id
    ,       LAG (var.status) OVER (PARTITION BY var.ventity_id ORDER BY action_date)                AS lag_status
    ,       LAG (var.isprotected) OVER (PARTITION BY var.ventity_id ORDER BY action_date)           AS lag_isprotected
    ,       LAG (var.dateofbirth) OVER (PARTITION BY var.ventity_id ORDER BY action_date)           AS lag_dateofbirth
    ,       LAG (var.gender) OVER (PARTITION BY var.ventity_id ORDER BY action_date)                AS lag_gender
    ,       LAG (var.sindigits) OVER (PARTITION BY var.ventity_id ORDER BY action_date)             AS lag_sindigits
    FROM    cpp_schema.ventity_ar@CdpP var
    WHERE   var.action_date BETWEEN TO_DATE('01-MAR-10','DD-MON-YY') AND TO_DATE('10-APR-10','DD-MON-YY')
    AND     var.ar_action_performed != 'RTRV'It may then be useful to put an index on (ACTION_DATE,AR_ACTION_PERFORMED) if one doesn't already exist.
    *::EDIT::*
    I noticed the large amount of NVL calls in your outer query. These NVLs could possibly be eliminated if you use the optional second and third arguments of the LAG analytical function. I'm not sure if this would improve performance but it may make the query more readable and maintainable.
    HTH!
    Edited by: Centinul on Apr 20, 2010 10:50 AM

  • T-SQL query performance (CLR func + webservice)

    Hi guys
    I have CLR function which accepts address as a parameter, calls geocoding webservice and returns some information (coordinates etc.)
    I run SQL query
    SELECT *FROM T CROSS APPLY CLR_Func(T.Address)F
    Table contains 8 million records and obviously query runs very slow.
    Do you know any nice way to improve performance in this situation?
    Thank you,
    Max

    No WHERE condition?  SQL Server will call the function 8 million times ....
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • SQL Query returns question marks

    I am seeing a SQL Query, executed via ADODB in VB, from a 10G client (don't know exact version) to a Sun Solaris based 9.2.0.5.0 Server return all question marks...Table queried consists of 3 columns, 2 varchar2, one long: Here query:
    SELECT SETTINGVALUE FROM EWORKFLO.CONFIG WHERE SETTINGGROUP='New test' AND SETTINGNAME='Single Page'
    The query results in 2576 question marks...(????? etc).
    Any idea what may be going on here?
    Thanks...
    Leendert

    Hello Tak,
    Thanks for replying. When this query is run from SQLPLUS we get a proper result back, that is the actual values from the SETTINGVALUE column. This is the LONG column and contains data like this:
    [Scan Section]
    DeviceTimeout=15
    Display=1
    hDCCreate=0
    Unit=0
    DialogTitle=
    IniFileName=c:\winnt\temp\kf.ini
    IniSectionName=Scan Section
    DeviceCache=1
    etc....etc....
    Depending on the settings created, the return string may vary in length.
    Leen

  • How to compare same SQL query performance in different DB servers.

    We have Production and Validation Environment of Oracle11g DB on two Solaris OSs.
    H/W and DB,etc configurations of two Oracle DBs are almost same in PROD and VAL.
    But we detected large SQL query performace difference in PROD DB and VAL DB in same SQL query.
    I would like to find and solve the cause of this situation.
    How could I do that ?
    I plan to compare SQL execution plan in PROD and VAL DB and index fragmentations.
    Before that I thought I need to keep same condition of DB statistics information in PROD and VAL DB.
    So, I plan to execute alter system FLUSH BUFFER_CACHE;
    But I am worring about bad effects of alter system FLUSH BUFFER_CACHE; to end users
    If we did alter system FLUSH BUFFER_CACHE; and got execution plan of that SQL query in the time end users do not use that system ,
    there is not large bad effect to end users after those operations?
    Could you please let me know the recomendation to compare SQL query performace ?

    Thank you.
    I got AWR report for only VAL DB server but it looks strange.
    Is there any thing wrong in DB or how to get AWR report ?
    Host Name
    Platform
    CPUs
    Cores
    Sockets
    Memory (GB)
    xxxx
    Solaris[tm] OE (64-bit)
    .00
    Snap Id
    Snap Time
    Sessions
    Cursors/Session
    Begin Snap:
    xxxx
    13-Apr-15 04:00:04
    End Snap:
    xxxx
    14-Apr-15 04:00:22
    Elapsed:
    1,440.30 (mins)
    DB Time:
    0.00 (mins)
    Report Summary
    Cache Sizes
    Begin
    End
    Buffer Cache:
    M
    M
    Std Block Size:
    K
    Shared Pool Size:
    0M
    0M
    Log Buffer:
    K
    Load Profile
    Per Second
    Per Transaction
    Per Exec
    Per Call
    DB Time(s):
    0.0
    0.0
    0.00
    0.00
    DB CPU(s):
    0.0
    0.0
    0.00
    0.00
    Redo size:
    Logical reads:
    0.0
    1.0
    Block changes:
    0.0
    1.0
    Physical reads:
    0.0
    1.0
    Physical writes:
    0.0
    1.0
    User calls:
    0.0
    1.0
    Parses:
    0.0
    1.0
    Hard parses:
    W/A MB processed:
    16.7
    1,442,472.0
    Logons:
    Executes:
    0.0
    1.0
    Rollbacks:
    Transactions:
    0.0
    Instance Efficiency Percentages (Target 100%)
    Buffer Nowait %:
    Redo NoWait %:
    Buffer Hit %:
    In-memory Sort %:
    Library Hit %:
    96.69
    Soft Parse %:
    Execute to Parse %:
    0.00
    Latch Hit %:
    Parse CPU to Parse Elapsd %:
    % Non-Parse CPU:
    Shared Pool Statistics
    Begin
    End
    Memory Usage %:
    % SQL with executions>1:
    34.82
    48.31
    % Memory for SQL w/exec>1:
    63.66
    73.05
    Top 5 Timed Foreground Events
    Event
    Waits
    Time(s)
    Avg wait (ms)
    % DB time
    Wait Class
    DB CPU
    0
    100.00
    Host CPU (CPUs: Cores: Sockets: )
    Load Average Begin
    Load Average End
    %User
    %System
    %WIO
    %Idle
    Instance CPU
    %Total CPU
    %Busy CPU
    %DB time waiting for CPU (Resource Manager)
    Memory Statistics
    Begin
    End
    Host Mem (MB):
    SGA use (MB):
    46,336.0
    46,336.0
    PGA use (MB):
    713.6
    662.6
    % Host Mem used for SGA+PGA:
    Time Model Statistics
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Operating System Statistics
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Operating System Statistics - Detail
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Foreground Wait Class
    s - second, ms - millisecond - 1000th of a second
    ordered by wait time desc, waits desc
    %Timeouts: value of 0 indicates value was < .5%. Value of null is truly 0
    Captured Time accounts for % of Total DB time .00 (s)
    Total FG Wait Time: (s) DB CPU time: .00 (s)
    Wait Class
    Waits
    %Time -outs
    Total Wait Time (s)
    Avg wait (ms)
    %DB time
    DB CPU
    0
    100.00
    Back to Wait Events Statistics
    Back to Top
    Foreground Wait Events
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Background Wait Events
    ordered by wait time desc, waits desc (idle events last)
    Only events with Total Wait Time (s) >= .001 are shown
    %Timeouts: value of 0 indicates value was < .5%. Value of null is truly 0
    Event
    Waits
    %Time -outs
    Total Wait Time (s)
    Avg wait (ms)
    Waits /txn
    % bg time
    log file parallel write
    527,034
    0
    2,209
    4
    527,034.00
    db file parallel write
    381,966
    0
    249
    1
    381,966.00
    os thread startup
    2,650
    0
    151
    57
    2,650.00
    latch: messages
    125,526
    0
    89
    1
    125,526.00
    control file sequential read
    148,662
    0
    54
    0
    148,662.00
    control file parallel write
    41,935
    0
    28
    1
    41,935.00
    Log archive I/O
    5,070
    0
    14
    3
    5,070.00
    Disk file operations I/O
    8,091
    0
    10
    1
    8,091.00
    log file sequential read
    3,024
    0
    6
    2
    3,024.00
    db file sequential read
    1,299
    0
    2
    2
    1,299.00
    latch: shared pool
    722
    0
    1
    1
    722.00
    enq: CF - contention
    4
    0
    1
    208
    4.00
    reliable message
    1,316
    0
    1
    1
    1,316.00
    log file sync
    71
    0
    1
    9
    71.00
    enq: CR - block range reuse ckpt
    36
    0
    0
    13
    36.00
    enq: JS - queue lock
    459
    0
    0
    1
    459.00
    log file single write
    414
    0
    0
    1
    414.00
    enq: PR - contention
    5
    0
    0
    57
    5.00
    asynch descriptor resize
    67,076
    100
    0
    0
    67,076.00
    LGWR wait for redo copy
    5,184
    0
    0
    0
    5,184.00
    rdbms ipc reply
    1,234
    0
    0
    0
    1,234.00
    ADR block file read
    384
    0
    0
    0
    384.00
    SQL*Net message to client
    189,490
    0
    0
    0
    189,490.00
    latch free
    559
    0
    0
    0
    559.00
    db file scattered read
    17
    0
    0
    6
    17.00
    resmgr:internal state change
    1
    100
    0
    100
    1.00
    direct path read
    301
    0
    0
    0
    301.00
    enq: RO - fast object reuse
    35
    0
    0
    2
    35.00
    direct path write
    122
    0
    0
    1
    122.00
    latch: cache buffers chains
    260
    0
    0
    0
    260.00
    db file parallel read
    1
    0
    0
    41
    1.00
    ADR file lock
    144
    0
    0
    0
    144.00
    latch: redo writing
    55
    0
    0
    1
    55.00
    ADR block file write
    120
    0
    0
    0
    120.00
    wait list latch free
    2
    0
    0
    10
    2.00
    latch: cache buffers lru chain
    44
    0
    0
    0
    44.00
    buffer busy waits
    3
    0
    0
    2
    3.00
    latch: call allocation
    57
    0
    0
    0
    57.00
    SQL*Net more data to client
    55
    0
    0
    0
    55.00
    ARCH wait for archivelog lock
    78
    0
    0
    0
    78.00
    rdbms ipc message
    3,157,653
    40
    4,058,370
    1285
    3,157,653.00
    Streams AQ: qmn slave idle wait
    11,826
    0
    172,828
    14614
    11,826.00
    DIAG idle wait
    170,978
    100
    172,681
    1010
    170,978.00
    dispatcher timer
    1,440
    100
    86,417
    60012
    1,440.00
    Streams AQ: qmn coordinator idle wait
    6,479
    48
    86,413
    13337
    6,479.00
    shared server idle wait
    2,879
    100
    86,401
    30011
    2,879.00
    Space Manager: slave idle wait
    17,258
    100
    86,324
    5002
    17,258.00
    pmon timer
    46,489
    62
    86,252
    1855
    46,489.00
    smon timer
    361
    66
    86,145
    238628
    361.00
    VKRM Idle
    1
    0
    14,401
    14400820
    1.00
    SQL*Net message from client
    253,909
    0
    419
    2
    253,909.00
    class slave wait
    379
    0
    0
    0
    379.00
    Back to Wait Events Statistics
    Back to Top
    Wait Event Histogram
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Wait Event Histogram Detail (64 msec to 2 sec)
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Wait Event Histogram Detail (4 sec to 2 min)
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Wait Event Histogram Detail (4 min to 1 hr)
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Service Statistics
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    Service Wait Class Stats
    No data exists for this section of the report.
    Back to Wait Events Statistics
    Back to Top
    SQL Statistics
    SQL ordered by Elapsed Time
    SQL ordered by CPU Time
    SQL ordered by User I/O Wait Time
    SQL ordered by Gets
    SQL ordered by Reads
    SQL ordered by Physical Reads (UnOptimized)
    SQL ordered by Executions
    SQL ordered by Parse Calls
    SQL ordered by Sharable Memory
    SQL ordered by Version Count
    Complete List of SQL Text
    Back to Top
    SQL ordered by Elapsed Time
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by CPU Time
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by User I/O Wait Time
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Gets
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Reads
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Physical Reads (UnOptimized)
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Executions
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Parse Calls
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Sharable Memory
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    SQL ordered by Version Count
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    Complete List of SQL Text
    No data exists for this section of the report.
    Back to SQL Statistics
    Back to Top
    Instance Activity Statistics
    Instance Activity Stats
    Instance Activity Stats - Absolute Values
    Instance Activity Stats - Thread Activity
    Back to Top
    Instance Activity Stats
    No data exists for this section of the report.
    Back to Instance Activity Statistics
    Back to Top
    Instance Activity Stats - Absolute Values
    No data exists for this section of the report.
    Back to Instance Activity Statistics
    Back to Top
    Instance Activity Stats - Thread Activity
    Statistics identified by '(derived)' come from sources other than SYSSTAT
    Statistic
    Total
    per Hour
    log switches (derived)
    69
    2.87
    Back to Instance Activity Statistics
    Back to Top
    IO Stats
    IOStat by Function summary
    IOStat by Filetype summary
    IOStat by Function/Filetype summary
    Tablespace IO Stats
    File IO Stats
    Back to Top
    IOStat by Function summary
    'Data' columns suffixed with M,G,T,P are in multiples of 1024 other columns suffixed with K,M,G,T,P are in multiples of 1000
    ordered by (Data Read + Write) desc
    Function Name
    Reads: Data
    Reqs per sec
    Data per sec
    Writes: Data
    Reqs per sec
    Data per sec
    Waits: Count
    Avg Tm(ms)
    Others
    28.8G
    20.55
    .340727
    16.7G
    2.65
    .198442
    1803K
    0.01
    Direct Reads
    43.6G
    57.09
    .517021
    411M
    0.59
    .004755
    0
    LGWR
    19M
    0.02
    .000219
    41.9G
    21.87
    .496493
    2760
    0.08
    Direct Writes
    16M
    0.00
    .000185
    8.9G
    1.77
    .105927
    0
    DBWR
    0M
    0.00
    0M
    6.7G
    4.42
    .079670
    0
    Buffer Cache Reads
    3.1G
    3.67
    .037318
    0M
    0.00
    0M
    260.1K
    3.96
    TOTAL:
    75.6G
    81.33
    .895473
    74.7G
    31.31
    .885290
    2065.8K
    0.51
    Back to IO Stats
    Back to Top
    IOStat by Filetype summary
    'Data' columns suffixed with M,G,T,P are in multiples of 1024 other columns suffixed with K,M,G,T,P are in multiples of 1000
    Small Read and Large Read are average service times, in milliseconds
    Ordered by (Data Read + Write) desc
    Filetype Name
    Reads: Data
    Reqs per sec
    Data per sec
    Writes: Data
    Reqs per sec
    Data per sec
    Small Read
    Large Read
    Data File
    53.2G
    78.33
    .630701
    8.9G
    7.04
    .105197
    0.37
    21.51
    Log File
    13.9G
    0.18
    .164213
    41.9G
    21.85
    .496123
    0.02
    2.93
    Archive Log
    0M
    0.00
    0M
    13.9G
    0.16
    .164213
    Temp File
    5.6G
    0.67
    .066213
    8.1G
    0.80
    .096496
    5.33
    3713.27
    Control File
    2.9G
    2.16
    .034333
    2G
    1.46
    .023247
    0.05
    19.98

  • TDE Table encryption SQL Query performance is very very slow

    Hi,
    We have done one column encryption for one table using TDE method with no salt option and it got impact the response time of sql query to 32 hours.
    Oracle database version is 10.2.0.5
    Example like
    alter table abc modify (numberx encrypt no salt);
    after encryption the SQL execution taking more time and below are the statement for the same.
    ================================
    declare fNumber cardx.numberx%TYPE;
    fCount integer :=0;
    fserno cardx.serno%TYPE;
    fcaccserno cardx.caccserno%TYPE;
    ftrxnfeeprofserno cardx.trxnfeeprofserno%TYPE;
    fstfinancial cardx.stfinancial%TYPE;
    fexpirydate cardx.expirydate%TYPE;
    fpreviousexpirydate cardx.previousexpirydate%TYPE;
    fexpirydatestatus cardx.expirydatestatus%TYPE;
    fblockeddate cardx.blockeddate%TYPE;
    fproduct cardx.product%TYPE;
    faccstmtsummaryind cardx.accstmtsummaryind%TYPE;
    finstitution_id cardx.institution_id%TYPE;
    fdefaultaccounttype cardx.defaultaccounttype%TYPE;
    flanguagecode cardx.languagecode%TYPE;
    froute integer;
    begin for i in (select c.numberx from cardx c where c.stgeneral='NORM')
    loop select c.serno, c.caccserno, c.trxnfeeprofserno, c.stfinancial, c.expirydate, c.previousexpirydate, c.expirydatestatus, c.blockeddate, c.product, c.accstmtsummaryind, c.institution_id, c.defaultaccounttype, c.languagecode, (select count(*) from caccountrouting ar where ar.cardxserno=c.serno and ar.rtrxntype=ISS_REWARDS.GetRewardTrxnTypeserno) into fserno, fcaccserno, ftrxnfeeprofserno, fstfinancial, fexpirydate, fpreviousexpirydate, fexpirydatestatus, fblockeddate, fproduct, faccstmtsummaryind, finstitution_id, fdefaultaccounttype, flanguagecode, froute from cardx c where c.numberx=i.numberx; fCount := fCount+1; end loop; dbms_output.put_line(fCount); end;
    ===============================
    Any help would be great appreciate
    Thanks,
    Mohammed.
    Edited by: Mohammed Yousuf on Oct 7, 2011 12:47 PM

    Still, that's not enough evidence to prove that TDE is indeed the culprit. Can you trace the query before and after enabling the TDE using 10046 and post it here.
    Aman....

  • Speed up SQL Query performance

    Hi,
    I am having a SQL query which has got some inner joins between tables.
    In this query i will be selecting values from set of values obtained by going through all rows in a table.
    I am using a inner join between two tables to achive this purpose.
    But, as the table which i go through all rows is extremely big it takes lot of time to go through all rows and the query slows down.
    Is there any other way by which i can speed up query.

    This is the out put of my test plan.
    Please suggest which one needs to be improved.
    PLAN_TABLE_OUTPUT
    Plan hash value: 3453987661
    | Id  | Operation                               | Name                           | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                        |                                |     3 |  1002 |  3920   (1)| 00:00:48 |
    |   1 |  SORT ORDER BY                          |                                |     3 |  1002 |  3920   (1)| 00:00:48 |
    |*  2 |   TABLE ACCESS BY INDEX ROWID           | AS_EVENT_CHR_DATA              |     1 |    17 |     4   (0)| 00:00:01 |
    |   3 |    NESTED LOOPS                         |                                |     3 |  1002 |  3919   (1)| 00:00:48 |
    |*  4 |     HASH JOIN                           |                                |     3 |   951 |  3907   (1)| 00:00:47 |
    |*  5 |      TABLE ACCESS FULL                  | EV_CHR_DATA_TYPE               |     1 |    46 |     2   (0)| 00:00:01 |
    |   6 |      TABLE ACCESS BY INDEX ROWID        | AS_EVENT_CHR_DATA              |   702 | 50544 |  3883   (1)| 00:00:47 |
    |   7 |       NESTED LOOPS                      |                                |   348 | 94308 |  3904   (1)| 00:00:47 |
    |   8 |        NESTED LOOPS                     |                                |     1 |   199 |    21   (5)| 00:00:01 |
    |   9 |         NESTED LOOPS                    |                                |     1 |   174 |    20   (5)| 00:00:01 |
    |* 10 |          HASH JOIN                      |                                |     1 |   127 |    18   (6)| 00:00:01 |
    |  11 |           NESTED LOOPS                  |                                |     1 |    95 |    13   (0)| 00:00:01 |
    |  12 |            NESTED LOOPS                 |                                |     1 |    60 |    12   (0)| 00:00:01 |
    |  13 |             NESTED LOOPS                |                                |     1 |    33 |    10   (0)| 00:00:01 |
    |  14 |              TABLE ACCESS BY INDEX ROWID| ASSET                          |     1 |    21 |     2   (0)| 00:00:01 |
    |* 15 |               INDEX UNIQUE SCAN         | SERIAL_NUMBER_K3               |     1 |       |     1   (0)| 00:00:01 |
    |* 16 |              INDEX FAST FULL SCAN       | SYS_C0053318                   |     1 |    12 |     8   (0)| 00:00:01 |
    |  17 |             TABLE ACCESS BY INDEX ROWID | SEGMENT_CHILD                  |     1 |    27 |     2   (0)| 00:00:01 |
    |* 18 |              INDEX RANGE SCAN           | SYS_C0053319                   |    12 |       |     1   (0)| 00:00:01 |
    |  19 |            TABLE ACCESS BY INDEX ROWID  | SEGMENT                        |     1 |    35 |     1   (0)| 00:00:01 |
    |* 20 |             INDEX UNIQUE SCAN           | SYS_C0053318                   |     1 |       |     0   (0)| 00:00:01 |
    |* 21 |           TABLE ACCESS FULL             | SEGMENT_TYPE                   |     1 |    32 |     4   (0)| 00:00:01 |
    |  22 |          TABLE ACCESS BY INDEX ROWID    | ASSET_ON_SEGMENT               |     1 |    47 |     2   (0)| 00:00:01 |
    |* 23 |           INDEX RANGE SCAN              | ASSET_ON_SEGME_UK8115533871153 |     1 |       |     1   (0)| 00:00:01 |
    |  24 |         TABLE ACCESS BY INDEX ROWID     | ASSET                          |     1 |    25 |     1   (0)| 00:00:01 |
    |* 25 |          INDEX UNIQUE SCAN              | SYS_C0053240                   |     1 |       |     0   (0)| 00:00:01 |
    |* 26 |        INDEX RANGE SCAN                 | AS_EV_CHR_DATA_ASSETPK         |  4673 |       |    28   (4)| 00:00:01 |
    |* 27 |     INDEX RANGE SCAN                    | SYS_C0053249                   |     5 |       |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - filter("PARAMETRIC_TAG_NAME"."DATA_VALUE"='EngineOilConsumption')
       4 - access("AS_EVENT_CHR_DATA"."EC_DB_SITE"="EV_CHR_DATA_TYPE"."EC_DB_SITE" AND
                  "AS_EVENT_CHR_DATA"."EC_DB_ID"="EV_CHR_DATA_TYPE"."EC_DB_ID" AND
                  "AS_EVENT_CHR_DATA"."EC_TYPE_CODE"="EV_CHR_DATA_TYPE"."EC_TYPE_CODE")
       5 - filter("EV_CHR_DATA_TYPE"."NAME"='servicing ptric time unit')
      10 - access("OILSEG"."SG_TYPE_CODE"="SEGMENT_TYPE"."SG_TYPE_CODE")
      15 - access("ASSET"."SERIAL_NUMBER"='30870')
      16 - filter("ASSET"."ASSET_ID"="SEGMENT"."SEGMENT_ID")
      18 - access("SEGMENT"."SEGMENT_SITE"="SEGMENT_CHILD"."SEGMENT_SITE" AND
                  "SEGMENT"."SEGMENT_ID"="SEGMENT_CHILD"."SEGMENT_ID")
      20 - access("SEGMENT_CHILD"."CHILD_SG_SITE"="OILSEG"."SEGMENT_SITE" AND
                  "SEGMENT_CHILD"."CHILD_SG_ID"="OILSEG"."SEGMENT_ID")
      21 - filter("SEGMENT_TYPE"."NAME"='Aircraft Equipment Engine Holder')
      23 - access("OILSEG"."SEGMENT_ID"="ASSET_ON_SEGMENT"."SEGMENT_ID")
      25 - access("ASSET_ON_SEGMENT"."ASSET_ORG_SITE"="OILASSET"."ASSET_ORG_SITE" AND
                  "ASSET_ON_SEGMENT"."ASSET_ID"="OILASSET"."ASSET_ID")
      26 - access("ASSET_ON_SEGMENT"."ASSET_ORG_SITE"="AS_EVENT_CHR_DATA"."ASSET_ORG_SITE" AND
                  "ASSET_ON_SEGMENT"."ASSET_ID"="AS_EVENT_CHR_DATA"."ASSET_ID")
      27 - access("AS_EVENT_CHR_DATA"."AS_EV_ID"="PARAMETRIC_TAG_NAME"."AS_EV_ID")

  • SQL Developer vs TOAD - query performance question

    Somebody made me notice same queries are executing slower in SQL Developer than in TOAD. I'm rather curious about this issue, since I understand Java is "slow" but I can't find any other thread about this point. I don't use TOAD, so I can't compare...
    Can this be related to the amount of data being returned by the query ? What could be the other reasons of SQL Dev running slower with an identical query ?
    Thanks,
    Attila

    It also occurs to me that TOAD always uses the equivalent of the JDBC "thick" driver. SQL Developer can use either the "thin" driver or the "thick" driver, but connections are usually configured with the "thin" driver, since you need an Oracle client to use the "thick" driver.
    The difference is that "thin" drivers are written entirely in Java, but "thick" drivers are written with only a little Java that calls the native executable (hence you need an Oracle client) to do most of the work. Theoretically, a thick driver is faster because the object code doesn't need to be interpreted by the JVM. However, I've heard that the difference in performance is not that large. The only way to know for sure is to configure a connection in SQL Developer to use the thick driver, and see if it is faster (I'd use a stop-watch).
    Someone correct me if I'm wrong, but I think that if you use "TNS" as your connection type, SQL Developer will use the thick driver, while the default, "Basic" connection type uses the thin driver. Otherwise, you're going to have to use the "Advanced" connection type and type in the Custom JDBC URL for the thick driver.

  • Sql query performance need to get improved

    hi all..
    i got performnace issue with my sp where i used 3 cte's.. i'm posting my code.please help me how can i improve the performance of query
    i created non-clustered indexes for tables based on the keys with which the tables are joined..
    USE [OPTM]
    GO
    /****** Object: StoredProcedure [dbo].[GetSample] Script Date: 01/07/2014 10:29:32 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [dbo].[GetSample]
    @StartDate DateTime,
    @EndDate DateTime,
    @Portfolio int,
    @Program int,
    @Project int
    AS
    Date Author Purpose
    06/11/2012 Ajeesh.C To get the Workitem details for the Scope Workitem Green chart Report.
    06/11/2012 Shinoj.P T-SQL re-structuring.
    Testing :
    exec [dbo].[GetSample] '01/01/2013','12/31/2013',-1,-1,-1
    exec [dbo].[GetSample] '01/01/2013','12/31/2013',16,24,199
    exec [dbo].[GetSample] '11/01/2013','12/31/2013',-1,-1,703
    exec [dbo].[GetSample] '11/01/2012','11/30/2012',8,-1,-1
    select * from tb_Portfolio
    BEGIN
    DECLARE @Scope nvarchar(250),@ScopeID int,@ProjectID int,@WorkItem nvarchar(250),@ProgramID int, @PortfolioID int;
    -------Added 3 columns(StatusID,Status,TaskID)--------
    CREATE TABLE #GrnChartTempTable
    AllocationDate datetime NULL,
    Division nvarchar(50) NULL,
    DivisionID int NULL,
    ResourceName nvarchar(250) NULL,
    ResourceEmailID nvarchar(max) NULL,
    ResourceID int NULL,
    Project nvarchar(250) NULL,
    ProjectID int NULL,
    Scope nvarchar(MAX) NULL,
    ScopeID int NULL,
    WorkItem nvarchar(MAX) NULL,
    TaskStartDate datetime NULL,
    TaskEndDate datetime NULL,
    ProgramID int NULL,
    Program nvarchar(250) NULL,
    PortfolioID int NULL,
    Portfolio nvarchar(250) NULL,
    StatusID int NULL,
    Status nvarchar(50) NULL,
    TaskID int null,
    EstimateHrs nvarchar(250) NULL,
    ScopeEstimateHrs int NULL,
    Allocated int NOT NULL
    WITH Datematrix(AllocationDate)
    As
    SELECT @StartDate AS AllocationDate
    UNION ALL
    SELECT DATEADD(D,1,AllocationDate) AS AllocationDate
    FROM Datematrix WHERE AllocationDate<@EndDate
    Allocation (Division,DivisionID,ResourceName,ResourceEmailID,ResourceID,Project
    ,ProjectID,Scope,ScopeID,WorkItem,TaskStartDate,TaskEndDate
    ,ProgramID ,Program,PortfolioID ,Portfolio,StatusID,Status,TaskID,EstimateHrs,ScopeEstimateHrs)
    AS
    SELECT
    DIV.Division
    ,RES.DivisionID
    ,RES.ResourceName
    ,ResourceEmailID = STUFF((
    SELECT COALESCE( ', ' + CONVERT(VARCHAR,RES.Email1), '')
    FROM dbo.TasksResource TSKRES WITH(NOLOCK) LEFT OUTER JOIN
    dbo.tb_Resource RES WITH(NOLOCK) ON RES.UID = TSKRES.ResourceID
    WHERE TSKRES.TaskID = TSK.TaskID
    FOR XML PATH('')), 1, 1, '')
    ,RES.UID ResourceID
    ,PRJ.Project + ' (' + CONVERT(VARCHAR(15),PRJ.StartDate,101) +' - ' + CONVERT(VARCHAR(15),PRJ.EndDate,101) + ')' as Project
    ,PRJ.UID ProjectID
    ,SCP.Title Scope
    ,SCP.ScopeID
    ,TSK.Title WorkItem
    ,TSK.StartDate TaskStartDate
    ,TSK.EndDate TaskEndDate
    ,PRJ.ProgramID
    ,PR.Program
    ,PR.PortfolioID
    ,PF.Portfolio
    ,TSK.StatusID
    ,ST.Status
    ,TSK.TaskID
    ,TSK.EstimateHrs
    ,(isnull(SCP.EstimateARCH,0) + isnull(SCP.EstimateBA,0) + isnull(SCP.EstimateDev,0) + isnull(SCP.EstimatePM,0) + isnull(SCP.EstimateQA,0) + isnull(SCP.EstimateRM,0)) as ScopeEstimateHrs
    --SCP.EstimateARCH + SCP.EstimateBA +SCP.EstimateDev +SCP.EstimatePM +SCP.EstimateQA +SCP.EstimateRM as ScopeEstimateHrs
    FROM Tasks TSK WITH(NOLOCK)
    INNER JOIN dbo.Scope SCP WITH(NOLOCK) ON TSK.ScopeID = SCP.ScopeID
    INNER JOIN dbo.tb_Project PRJ WITH(NOLOCK)ON TSK.ProjectID = PRJ.UID
    INNER JOIN dbo.tb_Program PR WITH(NOLOCK) ON PR.UID=PRJ.ProgramID
    INNER JOIN dbo.tb_Portfolio PF WITH(NOLOCK)ON PF.UID=PR.PortfolioID
    LEFT OUTER JOIN dbo.TasksResource TSKRES WITH(NOLOCK)ON TSKRES.TaskID = TSK.TaskID
    LEFT OUTER JOIN dbo.tb_Resource RES WITH(NOLOCK) ON RES.UID = TSKRES.ResourceID
    LEFT JOIN dbo.tb_Division DIV WITH(NOLOCK) ON RES.DivisionID = DIV.UID
    LEFT JOIN dbo.tb_Status ST WITH(NOLOCK) ON TSK.StatusID=ST.UID /*relating with the high level work items */
    WHERE (PRJ.UID = @Project OR @Project = -1)
    AND (PRJ.ProgramID = @Program OR @Program = -1)
    AND (PRJ.PortfolioID =@Portfolio OR @Portfolio = -1)
    MainData (AllocationDate,Division,DivisionID,ResourceName,ResourceEmailID,ResourceID,Project,ProjectID
    ,Scope,ScopeID,WorkItem,TaskStartDate,TaskEndDate
    ,ProgramID ,Program,PortfolioID ,Portfolio,StatusID,Status,TaskID,EstimateHrs,ScopeEstimateHrs,Allocated)
    AS
    ( SELECT
    Datematrix.*
    ,Allocation.*
    ,CASE WHEN ISDATE(TaskStartDate)=1 THEN 1 ELSE 0 END AS Allocated
    FROM Datematrix FULL OUTER JOIN Allocation
    ON ( Datematrix.AllocationDate>= Allocation.TaskStartDate
    AND Datematrix.AllocationDate<=Allocation.TaskEndDate
    INSERT INTO #GrnChartTempTable
    SELECT * FROM MainData
    OPTION (MAXRECURSION 0);
    SELECT TOP 1 @Scope=Scope,@ScopeID=ScopeID, @ProjectID=ProjectID
    ,@WorkItem=WorkItem,@ProgramID=ProgramID,@PortfolioID=PortfolioID
    FROM #GrnChartTempTable WHERE Scope IS NOT NULL AND ISDATE(AllocationDate)=1 ORDER BY Scope ;
    SELECT AllocationDate,Division,DivisionID
    ,ResourceName,ResourceEmailID,ResourceID,Project
    ,ISNULL(ProjectID,@ProjectID) ProjectID
    ,ISNULL(Scope,@Scope) Scope
    ,ISNULL(ScopeID,@ScopeID) ScopeID
    ,ISNULL(WorkItem,@WorkItem) WorkItem
    ,TaskStartDate,TaskEndDate
    ,ISNULL(ProgramID ,@ProgramID) ProgramID
    ,Program
    ,ISNULL(PortfolioID,@PortfolioID) PortfolioID
    ,Portfolio,StatusID,Status,TaskID,EstimateHrs,isnull(ScopeEstimateHrs,0)ScopeEstimateHrs,Allocated
    FROM #GrnChartTempTable MainData
    WHERE ISDATE(MainData.AllocationDate)=1
    AND ISNULL(Scope,@Scope) IS NOT NULL
    --WHERE FinalData.Scope IS NOT NULL
    END
    this is my code pls help..
    lucky

    You need to focus on optimizing your code by looking at the logic and removing any extraneous rows that you do not need - stop depending on the optimizer to do your work. 
    You have the following in multiple lines:   ISDATE(AllocationDate)=1
    Look at your final resultset.  You do not want any other rows (where isdate() <> 1) so stop selecting them in the first place. In addition, you are using a full outer join in the first query that uses this logic.  Since you do not qualify
    your columns with the tablename (or alias - which is a best practice), I cannot say if the isdate logic negates the full outer join - but I suspect it might.  I also question the logic behind the assignment of the local variables and their use in the
    final query.  You could remove the separate assignment query (and the variables) by simply moving that query into a derived table (or cte) of the final query.  That might not be a significant improvement (you did not give any indications about the size
    of the various queries) but I think it is simpler, more resilient, more obvious.  I also question the reasoning behind the use of a full outer join.
    Why do you left join to dbo.tb_Status?  Does not every task have a status?
    You join to the TaskResource and tb_Resource tables multiple times (in the Allocation cte) - and it appears that there is a 1/m relationship between task and this joined resultset.  Yet the primary query of the Allocation cte does no aggregation. 
    That is concerning, but I don't know your data so perhaps this is correct.  OTH, perhaps it depends on an assumption and your existing data has not yet violated that assumption. 
    But these are only guesses.  As Erland indicates, optimzing requires knowledge of the tables, the data, your business logic, etc. 

  • How to test SQL query performance - realiably?

    I have certain queries and I want to test which one is faster, and how big is the difference.
    How can I do this reliably?
    The problem is, when I execute the queries, Oracle does it's caching and execution planning and whatnot, and results of the queries are dependent on the order I execute them.
    Example: query A and query B, supposed to return same data.
    query A, run 1: 587 seconds
    query A, run 2: 509 seconds
    query B, run 1: 474 seconds
    query B, run 2: 451 seconds
    It would seem that A is somewhat faster than B, but if I change the order and execute B before A, results are different.
    Also I'm running the queries in SQL Developer, and it only returns 100 first lines, how can I remove this effect and simulate real scenario where all lines are fetched?
    I can also use EXPLAIN PLANs and look at the costs but I'm not sure how much I can trust those either. I understand they are only estimations and even if cost(a) = 1.5 * cost (b), b could still end up executing faster in practise due to inaccuracies in the cost calculation....right? EDIT: actually event if cost(a) = 5000 * cost(b), b can still execute faster.....seems like query A's cost is 15836 and B's cost is 3 while A seems to be faster in practise.
    Edited by: user620914 on 19-Jan-2010 01:42

    user620914 wrote:
    I have to say I don't understand your point either :)
    What are you saying, that people should not test their SQL performance? That tools such as autotrace are useless?No.. what I'm saying is that you need a baseline to make an informed decision about SQL performance.
    What does a 4 second SQL performance mean for query foo ? Nothing really.. wearing my dba cap I would point at that this is actually utterly useless for me to determine the impact of your query on production, or use it to determine how to scale it.
    If instead you tell me that is hits that table using an index range scan.. I know what it is doing and have a far better idea what it will do to the production instance.
    Thus my questioning this "+elapsed time+" measurement approach. I as a dba cannot use it... and I'm not sure what benefit (wearing my developer hat) you will find from it either.
    You can form your SQL queries better or worse, or select your table structure / indexes better or worse. Some choices may end up executing orders of magnitude slower than others. Obviously you can't get exact measurements "this query executes in 43123 ns" and there are a lot of unpredictable variables that affect the end performance. Still, it's often better to test your querie's / table's performance before implementing them in the application than not.Exactly. I'm not questioning the fact that optimising your code (and ALL your code, not just SQL) is a Good Thing (tm) - but how you go about that optimisation process.
    For example, your PL/SQL code fires off a query. It returns on average 10,000 rows, hits a single partition (SQL enables partitioning pruning) and then uses a local bitmap index to identify the rows.
    An optimal query by the sounds of it, and one that will perform and scale well.. even when the database instance needs to service a 100 clients using your code and running this query.
    Only, the code does a single bulk collect of all the rows and stuff it into dedicated process memory (PGA). Servicing a 100 clients means that dedicated server memory is now needed for 100x10000 rows - there's insufficient free memory, causing the kernel to start swapping pages in and out of memory heavily as all 100 client sessions are active and wanting to process the rows returned by the optimal query.
    What happens to scalability and performance now?
    Testing for performance is not simply measuring a query and then trying to use that or extrapolate that to determine application performance and the impact on production.
    It starts with the design of the tables, the design of the application, the writing of the code (application and SQL). It is not something that should be done after the fact as in "+okay, application all done, let's see how she performs!+".. and especially not using time as the baseline for performance measurement.

  • Which SQL query performance is better

    Putting this in a new thread so that i dont confuse and mix the query with my similiar threads.
    Based on all of your suggestions for the below query,i finally came up with 2 RESOLUTIONS possible for it.
    So,which would be the best in PERFORMANCE from the 2 resolutions i pasted below?I mean which will PERFORM FASTER and is more effecient.
    ***The original QUERY is at the bottom.
    Resolution 1:-/***Divided into 2 sep. queries and using UNION ALL ****/ Is UNION ALL costly?
    SELECT null, null, null, null, null,null, null, null, null,
    null,null, null, null, null, null,null,null, count(*) as total_results
    FROM
    test_person p,
    test_contact c1,
    test_org_person porg
    WHERE p.CLM_ID ='11' and
    p.person_id = c1.ref_id(+)
    AND p.person_id = porg.o_person_id
    and porg.O_ORG_ID ='11'
    UNION ALL
    SELECT lastname, firstname,person_id, middlename,socsecnumber,
    birthday, U_NAME,
    U_ID,
    PERSON_XML_DATA,
    BUSPHONE,
    EMLNAME,
    ORG_NAME,
    EMPID,
    EMPSTATUS,
    DEPARTMENT,
    org_relationship,
    enterprise_name,
    null
    FROM
    SELECT
    beta.*, rownum as alpha
    FROM
    SELECT
    p.lastname, p.firstname, p.person_id, p.middlename, p.socsecnumber,
    to_char(p.birthday,'mm-dd-yyyy') as birthday, p.username as U_NAME,
    p.clm_id as U_ID,
    p.PERSON_XML_DATA.extract('/').getStringVal() AS PERSON_XML_DATA,
    c1.CONTACT_DATA.extract('//phone[1]/number/text()').getStringVal() AS BUSPHONE,
    c1.CONTACT_DATA.extract('//email[2]/address/text()').getStringVal() AS EMLNAME,
    c1.CONTACT_DATA.extract('//company/text()').getStringVal() AS ORG_NAME,
    porg.emplid as EMPID, porg.empl_status as EMPSTATUS, porg.DEPARTMENT,
    porg.org_relationship,
    porg.enterprise_name
    FROM
    test_person p,
    test_contact c1,
    test_org_person porg
    WHERE p.CLM_ID ='11' and
    p.person_id = c1.ref_id(+)
    AND p.person_id = porg.o_person_id
    and porg.O_ORG_ID ='11'
    ORDER BY
    upper(p.lastname), upper(p.firstname)
    ) beta
    WHERE
    alpha BETWEEN 1 AND 100
    Resolution 2:-
    /****here,the INNER most count query is removed ****/
    select *
    FROM
    SELECT
    beta.*, rownum as alpha
    FROM
    SELECT
    p.lastname, p.firstname, p.person_id, p.middlename, p.socsecnumber,
    to_char(p.birthday,'mm-dd-yyyy') as birthday, p.username as U_NAME,
    p.clm_id as U_ID,
    p.PERSON_XML_DATA.extract('/').getStringVal() AS PERSON_XML_DATA,
    c1.CONTACT_DATA.extract('//phone[1]/number/text()').getStringVal() AS BUSPHONE,
    c1.CONTACT_DATA.extract('//email[2]/address/text()').getStringVal() AS EMLNAME,
    c1.CONTACT_DATA.extract('//company/text()').getStringVal() AS ORG_NAME,
    porg.emplid as EMPID, porg.empl_status as EMPSTATUS, porg.DEPARTMENT,
    porg.org_relationship,
    porg.enterprise_name,
    COUNT(*) OVER () cnt -----This is the function
    FROM
    test_person p,
    test_contact c1,
    test_org_person porg
    WHERE p.CLM_ID ='11' and
    p.person_id = c1.ref_id(+)
    AND p.person_id = porg.o_person_id
    and porg.O_ORG_ID ='11'
    ORDER BY upper(p.lastname), upper(p.firstname)
    ) beta
    WHERE
    alpha BETWEEN 1 AND 100
    ORIGINAL QUERY
    SELECT
    FROM
    SELECT
    beta.*, rownum as alpha
    FROM
    SELECT
    p.lastname, p.firstname, porg.DEPARTMENT,
    porg.org_relationship,
    porg.enterprise_name,
    SELECT
    count(*)
    FROM
    test_person p, test_contact c1, test_org_person porg
    WHERE
    p.p_id = c1.ref_id(+)
    AND p.p_id = porg.o_p_id
    $where_clause$
    ) AS results
    FROM
    test_person p, test_contact c1, test_org_person porg
    WHERE
    p.p_id = c1.ref_id(+)
    AND p.p_id = porg.o_p_id
    $where_clause$
    ORDER BY
    upper(p.lastname), upper(p.firstname)
    ) beta
    WHERE
    alpha BETWEEN #startRec# AND #endRec#

    I have now run the explain plans and put them below seperately for each SQL.The SQL queries for each of the items are posted in the 1st post of this thread.
    ***The original QUERY is at the bottom.
    Resolution 1:-/***Divided into 2 sep. queries and using UNION ALL ****/ Is UNION ALL costly?
    EXPLAIN PLANS SECTION
    1- Original
    Plan hash value: 1981931315
    | Id  | Operation                           | Name               | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                    |                    | 22859 |   187M|       | 26722  (81)| 00:05:21 |
    |   1 |  UNION-ALL                          |                    |       |       |       |            |          |
    |   2 |   SORT AGGREGATE                    |                    |     1 |    68 |       |            |          |
    |   3 |    MERGE JOIN OUTER                 |                    | 22858 |  1517K|       |  5290   (1)| 00:01:04 |
    |   4 |     MERGE JOIN                      |                    | 22858 |   982K|       |  4304   (1)| 00:00:52 |
    |*  5 |      INDEX RANGE SCAN               | test_org_person_I3 | 24155 |   542K|       |   363   (1)| 00:00:05 |
    |*  6 |      SORT JOIN                      |                    | 22858 |   468K|  1448K|  3941   (1)| 00:00:48 |
    |*  7 |       TABLE ACCESS FULL             | test_PERSON        | 22858 |   468K|       |  3716   (1)| 00:00:45 |
    |*  8 |     SORT JOIN                       |                    | 68472 |  1604K|  4312K|   985   (2)| 00:00:12 |
    |   9 |      INDEX FAST FULL SCAN           | test_CONTACT_FK1   | 68472 |  1604K|       |   113   (1)| 00:00:02 |
    |* 10 |   VIEW                              |                    | 22858 |   187M|       | 21433   (1)| 00:04:18 |
    |  11 |    COUNT                            |                    |       |       |       |            |          |
    |  12 |     VIEW                            |                    | 22858 |   187M|       | 21433   (1)| 00:04:18 |
    |  13 |      SORT ORDER BY                  |                    | 22858 |  6875K|    14M| 21433   (1)| 00:04:18 |
    |  14 |       MERGE JOIN OUTER              |                    | 22858 |  6875K|       | 18304   (1)| 00:03:40 |
    |  15 |        MERGE JOIN                   |                    | 22858 |  4397K|       | 11337   (1)| 00:02:17 |
    |  16 |         SORT JOIN                   |                    | 22858 |  3013K|  7192K|  5148   (1)| 00:01:02 |
    |* 17 |          TABLE ACCESS FULL          | test_PERSON        | 22858 |  3013K|       |  3716   (1)| 00:00:45 |
    |* 18 |         SORT JOIN                   |                    | 24155 |  1462K|  3800K|  6189   (1)| 00:01:15 |
    |  19 |          TABLE ACCESS BY INDEX ROWID| test_ORG_PERSON    | 24155 |  1462K|       |  5535   (1)| 00:01:07 |
    |* 20 |           INDEX RANGE SCAN          | test_ORG_PERSON_FK1| 24155 |       |       |   102   (1)| 00:00:02 |
    |* 21 |        SORT JOIN                    |                    | 68472 |  7422K|    15M|  6968   (1)| 00:01:24 |
    |  22 |         TABLE ACCESS FULL           | test_CONTACT       | 68472 |  7422K|       |  2895   (1)| 00:00:35 |
    Predicate Information (identified by operation id):
       5 - access("PORG"."O_ORG_ID"='11')
       6 - access("P"."PERSON_ID"="PORG"."O_PERSON_ID")
           filter("P"."PERSON_ID"="PORG"."O_PERSON_ID")
       7 - filter("P"."CLM_ID"='11')
       8 - access("P"."PERSON_ID"="C1"."REF_ID"(+))
           filter("P"."PERSON_ID"="C1"."REF_ID"(+))
      10 - filter("ALPHA"<=25 AND "ALPHA">=1)
      17 - filter("P"."CLM_ID"='11')
      18 - access("P"."PERSON_ID"="PORG"."O_PERSON_ID")
           filter("P"."PERSON_ID"="PORG"."O_PERSON_ID")
      20 - access("PORG"."O_ORG_ID"='11')
      21 - access("P"."PERSON_ID"="C1"."REF_ID"(+))
           filter("P"."PERSON_ID"="C1"."REF_ID"(+))
    -------------------------------------------------------------------------------terprise_name
    Resolution 2:-
    EXPLAIN PLANS SECTION
    1- Original
    Plan hash value: 1720299348
    | Id  | Operation                          | Name               | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                   |                    | 23518 |    13M|       | 11545   (1)| 00:02:19 |
    |*  1 |  VIEW                              |                    | 23518 |    13M|       | 11545   (1)| 00:02:19 |
    |   2 |   COUNT                            |                    |       |       |       |            |          |
    |   3 |    VIEW                            |                    | 23518 |    13M|       | 11545   (1)| 00:02:19 |
    |   4 |     WINDOW SORT                    |                    | 23518 |  3536K|       | 11545   (1)| 00:02:19 |
    |   5 |      MERGE JOIN OUTER              |                    | 23518 |  3536K|       | 11545   (1)| 00:02:19 |
    |   6 |       MERGE JOIN                   |                    | 23518 |  2985K|       | 10587   (1)| 00:02:08 |
    |   7 |        SORT JOIN                   |                    | 23518 |  1561K|  4104K|  4397   (1)| 00:00:53 |
    |*  8 |         TABLE ACCESS FULL          | test_PERSON        | 23518 |  1561K|       |  3716   (1)| 00:00:45 |
    |*  9 |        SORT JOIN                   |                    | 24155 |  1462K|  3800K|  6189   (1)| 00:01:15 |
    |  10 |         TABLE ACCESS BY INDEX ROWID| test_ORG_PERSON    | 24155 |  1462K|       |  5535   (1)| 00:01:07 |
    |* 11 |          INDEX RANGE SCAN          | test_ORG_PERSON_FK1| 24155 |       |       |   102   (1)| 00:00:02 |
    |* 12 |       SORT JOIN                    |                    | 66873 |  1567K|  4216K|   958   (2)| 00:00:12 |
    |  13 |        INDEX FAST FULL SCAN        | test_CONTACT_FK1   | 66873 |  1567K|       |   110   (1)| 00:00:02 |
    Predicate Information (identified by operation id):
       1 - filter("ALPHA"<=25 AND "ALPHA">=1)
       8 - filter("P"."CLM_ID"='11')
       9 - access("P"."PERSON_ID"="PORG"."O_PERSON_ID")
           filter("P"."PERSON_ID"="PORG"."O_PERSON_ID")
      11 - access("PORG"."O_ORG_ID"='11')
      12 - access("P"."PERSON_ID"="C1"."REF_ID"(+))
           filter("P"."PERSON_ID"="C1"."REF_ID"(+))
    ORIGINAL QUERY
    EXPLAIN PLANS SECTION
    1- Original
    Plan hash value: 319284042
    | Id  | Operation                          | Name               | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                   |                    | 22858 |   187M|       | 21433   (1)| 00:04:18 |
    |*  1 |  VIEW                              |                    | 22858 |   187M|       | 21433   (1)| 00:04:18 |
    |   2 |   COUNT                            |                    |       |       |       |            |          |
    |   3 |    VIEW                            |                    | 22858 |   187M|       | 21433   (1)| 00:04:18 |
    |   4 |     SORT ORDER BY                  |                    | 22858 |  6875K|    14M| 21433   (1)| 00:04:18 |
    |   5 |      MERGE JOIN OUTER              |                    | 22858 |  6875K|       | 18304   (1)| 00:03:40 |
    |   6 |       MERGE JOIN                   |                    | 22858 |  4397K|       | 11337   (1)| 00:02:17 |
    |   7 |        SORT JOIN                   |                    | 22858 |  3013K|  7192K|  5148   (1)| 00:01:02 |
    |*  8 |         TABLE ACCESS FULL          | test_PERSON        | 22858 |  3013K|       |  3716   (1)| 00:00:45 |
    |*  9 |        SORT JOIN                   |                    | 24155 |  1462K|  3800K|  6189   (1)| 00:01:15 |
    |  10 |         TABLE ACCESS BY INDEX ROWID| test_ORG_PERSON    | 24155 |  1462K|       |  5535   (1)| 00:01:07 |
    |* 11 |          INDEX RANGE SCAN          | test_ORG_PERSON_FK1| 24155 |       |       |   102   (1)| 00:00:02 |
    |* 12 |       SORT JOIN                    |                    | 68472 |  7422K|    15M|  6968   (1)| 00:01:24 |
    |  13 |        TABLE ACCESS FULL           | test_CONTACT       | 68472 |  7422K|       |  2895   (1)| 00:00:35 |
    Predicate Information (identified by operation id):
       1 - filter("ALPHA"<=25 AND "ALPHA">=1)
       8 - filter("P"."CLM_ID"='1862')
       9 - access("P"."PERSON_ID"="PORG"."O_PERSON_ID")
           filter("P"."PERSON_ID"="PORG"."O_PERSON_ID")
      11 - access("PORG"."O_ORG_ID"='1862')
      12 - access("P"."PERSON_ID"="C1"."REF_ID"(+))
           filter("P"."PERSON_ID"="C1"."REF_ID"(+))
    -------------------------------------------------------------------------------Edited by: user10817659 on Feb 19, 2009 11:47 PM
    Edited by: user10817659 on Feb 21, 2009 12:23 AM

  • SQL Query Performance Issue

    Hey,
    Please forgive me if I'm missing something really obvious but it's been a while since I did any SQL work and I'm obviously a bit rusty.
    When the below query is run the CPU on the SQL server maxes out. The query itself takes over 6 hours to run.
    Is there anything glaringly obvious with the query that might be causing thisCheers
    Paul
    SELECT TOP (100) PERCENT dbo.CUSTPACKINGSLIPTRANS.ITEMID AS [Stock Code],
    dbo.CUSTPACKINGSLIPTRANS.SALESUNIT AS [Unit of Sale],
    dbo.DIMENSIONFINANCIALTAG.DESCRIPTION AS [Product Group],
    dbo.INVENTITEMGROUP.ITEMGROUPID AS [Item Group],
    dbo.INVENTTABLE.SECTION,
    dbo.INVENTTABLE.GROUPS AS [Group],
    dbo.INVENTTABLE.SUBGROUPS AS [Sub Group],
    dbo.CUSTPACKINGSLIPJOUR.ORDERACCOUNT AS [Cust Account],
    dbo.CUSTTABLE.INVOICEACCOUNT AS [Invoice Account],
    dbo.DIRPARTYTABLE.NAME AS [Cust Name],
    dbo.CUSTTABLE.CURRENCY,
    dbo.CUSTTABLE.CIT_CONTROLLER AS [Credit Controller],
    dbo.CUSTTABLE.CREDITMAX AS [Credit Limit],
    dbo.CUSTTABLE.CUSTCLASSIFICATIONID AS Classification,
    dbo.DIRPERSONNAME.FIRSTNAME + ' ' + dbo.DIRPERSONNAME.LASTNAME AS [Sales Person],
    dbo.SALESTABLE.SALESGROUP AS [Outside Rooms],
    CASE WHEN CUSTTABLE.CUSTCLASSIFICATIONID = 'Cash' THEN dbo.SALESTABLE.SALESGROUP ELSE dbo.CUSTTABLE.SALESGROUP END AS [Sales Rep],
    dbo.LOGISTICSPOSTALADDRESS.STATE [Customer Region],
    dbo.LOGISTICSPOSTALADDRESS.COUNTY [Customer County],
    dbo.CUSTTABLE.LINEOFBUSINESSID AS [Line Of Business],
    a.DISPLAYVALUE AS [Site/Location],
    dbo.CUSTPACKINGSLIPTRANS.PACKINGSLIPID AS [Delivery Ref],
    dbo.LOGISTICSPOSTALADDRESS.COUNTRYREGIONID,
    CONVERT(varchar(12), dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE, 111) AS [Delivery Date],
    dbo.LOGISTICSPOSTALADDRESS.ADDRESS AS [Delivery Address],
    dbo.CUSTPACKINGSLIPTRANS.VALUEMST AS [Delivery Value (CON)],
    CONVERT(varchar(12), dbo.SALESTABLE.RECEIPTDATEREQUESTED, 111) AS [Requested Delivery Date],
    dbo.SALESTABLE.SALESID AS [Order Ref],
    CASE dbo.SALESTABLE.SALESSTATUS WHEN '0' THEN 'None' WHEN '1' THEN 'Open Order' WHEN '2' THEN 'Delivered' WHEN '3' THEN 'Invoiced' WHEN '4' THEN 'Canceled' END AS [Sales Status],
    CASE dbo.SALESTABLE.SALESTYPE WHEN '0' THEN 'Journal' WHEN '1' THEN 'Quotation' WHEN '2' THEN 'Subscription' WHEN '3' THEN 'Sales Order' WHEN '4' THEN 'Returned Item' WHEN '5' THEN 'Blanket Order' WHEN '6' THEN 'Item Requirements' WHEN '7' THEN 'Undefined' END AS [Sales Type],
    CASE dbo.SALESTABLE.AG_SALESLOCATION WHEN '0' THEN 'None' WHEN '1' THEN 'OR_DGN' WHEN '2' THEN 'OR_FMT' WHEN '3' THEN 'OR_TME' WHEN '4' THEN 'OR_OMA' WHEN '5' THEN 'DSP_DGN' WHEN '6' THEN 'DSP_FMT' WHEN '7' THEN 'DSP_TME' WHEN '8' THEN 'DSP_OMA' WHEN '9' THEN 'DSP_BEL' WHEN '10' THEN 'DSP_CDF' WHEN '11' THEN 'DSP_BGY' WHEN '12' THEN 'Credit Control' WHEN '13' THEN 'Internal Sales' WHEN '14' THEN 'CP_FMT' WHEN '15' THEN 'GBSales' END AS [Sales Location],
    dbo.SALESTABLE.PURCHORDERFORMNUM AS [Customer Requisition],
    dbo.SALESLINE.LINEDISC AS [Line Disc],
    dbo.SALESLINE.LINEPERCENT AS [Line Percent],
    dbo.SALESLINE.PRICEGROUPID AS [Price Group],
    dbo.INVENTDIM.INVENTLOCATIONID AS Warehouse,
    dbo.DIRPARTYTABLE.NAMEALIAS AS [Search Name],
    dbo.CUSTPACKINGSLIPJOUR.LORRYID AS [Lorry ID],
    dbo.CUSTPACKINGSLIPJOUR.LORRYREGNO AS [Lorry Reg],
    dbo.CUSTPACKINGSLIPJOUR.LORRYDRIVER AS [Lorry Driver],
    CASE dbo.SALESLINE.BLOCKED WHEN '0' THEN 'No' WHEN '1' THEN 'Yes' END AS [Stopped?],
    dbo.CUSTPACKINGSLIPTRANS.QTY AS [Qty Delivered],
    dbo.SALESLINE.SALESPRICE AS [Unit Price],
    dbo.CUSTPACKINGSLIPJOUR.CREATEDBY AS [SDN Creator],
    MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS Month,
    YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS Year,
    DATEPART(week, dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS WeekNo,
    CASE MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) WHEN '1' THEN '10' WHEN '2' THEN '11' WHEN '3' THEN '12' WHEN '4' THEN '1' WHEN '5' THEN '2' WHEN '6' THEN '3' WHEN '7' THEN '4' WHEN '8' THEN '5' WHEN '9' THEN '6' WHEN '10' THEN '7' WHEN '11' THEN '8' WHEN '12' THEN '9' END AS [Fin Period], CASE WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) <= '3' THEN CONVERT(VARCHAR(10), (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) - 1)) + '/' + CONVERT(VARCHAR(10), YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE)) WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) >= '4' THEN CONVERT(VARCHAR(10), YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE)) + '/' + CONVERT(VARCHAR(10), (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) + 1)) END AS [Fin Year],
    CASE WHEN dbo.custpackingsliptrans.salesunit = '100' THEN dbo.CUSTPACKINGSLIPTRANS.SALESUNIT * dbo.CUSTPACKINGSLIPTRANS.QTY WHEN dbo.custpackingsliptrans.salesunit = '1000' THEN dbo.CUSTPACKINGSLIPTRANS.SALESUNIT * dbo.CUSTPACKINGSLIPTRANS.QTY ELSE dbo.CUSTPACKINGSLIPTRANS.QTY END AS [No of Units],
    CASE dbo.INVENTITEMGROUPITEM.ITEMGROUPID WHEN 'Mortar' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Sand' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Decorative Gravel' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Crushed Aggregates' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Lintels' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 WHEN 'TBeams' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 WHEN 'Aggregates' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Lime' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY * dbo.UNITOFMEASURECONVERSION.FACTOR) WHEN 'Readymix' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 ELSE (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY * dbo.UNITOFMEASURECONVERSION.FACTOR) / 1000 END AS Tonnage,
    dbo.INVENTTABLE.NETWEIGHT AS [Net Weight],
    dbo.INVENTTABLE.PRODCOSTA,
    dbo.INVENTTABLE.PRODCOSTB,
    dbo.INVENTTABLE.PRODCOSTC,
    dbo.INVENTTABLE.PRODCOSTD,
    dbo.INVENTTABLE.PRODCOSTE,
    dbo.INVENTTABLE.PRODCOSTF,
    dbo.INVENTTABLE.PRODCOSTG,
    dbo.INVENTTABLE.PRODCOSTH,
    dbo.INVENTTABLE.QTYPERBALE,
    dbo.INVENTTABLE.M2PERBALE,
    dbo.SALESTABLE.SALESTYPE,
    dbo.SALESTABLE.DLVMODE AS [Delivery Mode],
    CONVERT(varchar(12), dbo.SALESTABLE.SHIPPINGDATECONFIRMED, 111) AS [Shipping Date Confirmed],
    CONVERT(varchar(12), dbo.SALESTABLE.CREATEDDATETIME, 111) AS [Created Date],
    dbo.SALESLINE.CUSTGROUP AS [Cust Group],
    dbo.INVENTTABLE.MADETOORDER AS [Made To Order]
    FROM dbo.CUSTPACKINGSLIPTRANS INNER JOIN
    dbo.CUSTPACKINGSLIPJOUR ON dbo.CUSTPACKINGSLIPTRANS.PACKINGSLIPID = dbo.CUSTPACKINGSLIPJOUR.PACKINGSLIPID INNER JOIN
    dbo.SALESLINE ON dbo.CUSTPACKINGSLIPJOUR.SALESID = dbo.SALESLINE.SALESID AND
    dbo.CUSTPACKINGSLIPTRANS.INVENTTRANSID = dbo.SALESLINE.INVENTTRANSID INNER JOIN
    dbo.INVENTTABLE ON dbo.CUSTPACKINGSLIPTRANS.ITEMID = dbo.INVENTTABLE.ITEMID INNER JOIN
    dbo.INVENTITEMGROUPITEM ON dbo.INVENTTABLE.ITEMID = dbo.INVENTITEMGROUPITEM.ITEMID INNER JOIN
    dbo.INVENTITEMGROUP ON dbo.INVENTITEMGROUPITEM.ITEMGROUPID = dbo.INVENTITEMGROUP.ITEMGROUPID INNER JOIN
    dbo.INVENTDIM ON dbo.SALESLINE.INVENTDIMID = dbo.INVENTDIM.INVENTDIMID INNER JOIN
    dbo.CUSTTABLE ON dbo.CUSTPACKINGSLIPJOUR.ORDERACCOUNT = dbo.CUSTTABLE.ACCOUNTNUM INNER JOIN
    dbo.DIRPARTYTABLE ON dbo.CUSTTABLE.PARTY = dbo.DIRPARTYTABLE.RECID INNER JOIN
    dbo.LOGISTICSPOSTALADDRESS ON dbo.DIRPARTYTABLE.PRIMARYADDRESSLOCATION = dbo.LOGISTICSPOSTALADDRESS.LOCATION INNER JOIN
    dbo.SALESTABLE ON dbo.SALESLINE.SALESID = dbo.SALESTABLE.SALESID INNER JOIN
    dbo.DIRPERSONNAME ON dbo.SALESTABLE.WORKERSALESTAKER = dbo.DIRPERSONNAME.RECID INNER JOIN
    dbo.ECORESPRODUCT ON dbo.CUSTPACKINGSLIPTRANS.ITEMID = dbo.ECORESPRODUCT.SEARCHNAME
    AND dbo.INVENTTABLE.ITEMID = dbo.ECORESPRODUCT.DISPLAYPRODUCTNUMBER LEFT OUTER JOIN
    dbo.UNITOFMEASURECONVERSION ON dbo.ECORESPRODUCT.RECID = dbo.UNITOFMEASURECONVERSION.PRODUCT LEFT OUTER JOIN
    dbo.UNITOFMEASURE ON dbo.UNITOFMEASURECONVERSION.TOUNITOFMEASURE = dbo.UNITOFMEASURE.RECID INNER JOIN
    dbo.DEFAULTDIMENSIONVIEW a ON dbo.CUSTPACKINGSLIPTRANS.DEFAULTDIMENSION = a.DEFAULTDIMENSION AND a.NAME = 'Department' LEFT OUTER JOIN
    dbo.DEFAULTDIMENSIONVIEW b ON dbo.INVENTTABLE.DEFAULTDIMENSION = b.DEFAULTDIMENSION AND b.NAME = 'Center' INNER JOIN
    dbo.DIMENSIONFINANCIALTAG ON b.ENTITYINSTANCE = dbo.DIMENSIONFINANCIALTAG.RECID
    WHERE (dbo.CUSTPACKINGSLIPTRANS.DATAAREAID = 'agl') AND
    (dbo.CUSTPACKINGSLIPJOUR.DATAAREAID = 'agl') AND
    (dbo.SALESLINE.DATAAREAID = 'agl') AND
    (dbo.INVENTTABLE.DATAAREAID = 'vuk') AND
    (dbo.INVENTDIM.DATAAREAID = 'agl') AND
    (dbo.CUSTTABLE.DATAAREAID = 'agl') AND
    (dbo.SALESTABLE.DATAAREAID = 'agl') AND
    (CASE WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) <= '3' THEN (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) - 1)
    WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) >= '4' THEN YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) END = 2014)

    Hey,
    Please forgive me if I'm missing something really obvious but it's been a while since I did any SQL work and I'm obviously a bit rusty.
    When the below query is run the CPU on the SQL server maxes out. The query itself takes over 6 hours to run.
    Is there anything glaringly obvious with the query that might be causing thisCheers
    Paul
    SELECT TOP (100) PERCENT dbo.CUSTPACKINGSLIPTRANS.ITEMID AS [Stock Code],
    dbo.CUSTPACKINGSLIPTRANS.SALESUNIT AS [Unit of Sale],
    dbo.DIMENSIONFINANCIALTAG.DESCRIPTION AS [Product Group],
    dbo.INVENTITEMGROUP.ITEMGROUPID AS [Item Group],
    dbo.INVENTTABLE.SECTION,
    dbo.INVENTTABLE.GROUPS AS [Group],
    dbo.INVENTTABLE.SUBGROUPS AS [Sub Group],
    dbo.CUSTPACKINGSLIPJOUR.ORDERACCOUNT AS [Cust Account],
    dbo.CUSTTABLE.INVOICEACCOUNT AS [Invoice Account],
    dbo.DIRPARTYTABLE.NAME AS [Cust Name],
    dbo.CUSTTABLE.CURRENCY,
    dbo.CUSTTABLE.CIT_CONTROLLER AS [Credit Controller],
    dbo.CUSTTABLE.CREDITMAX AS [Credit Limit],
    dbo.CUSTTABLE.CUSTCLASSIFICATIONID AS Classification,
    dbo.DIRPERSONNAME.FIRSTNAME + ' ' + dbo.DIRPERSONNAME.LASTNAME AS [Sales Person],
    dbo.SALESTABLE.SALESGROUP AS [Outside Rooms],
    CASE WHEN CUSTTABLE.CUSTCLASSIFICATIONID = 'Cash' THEN dbo.SALESTABLE.SALESGROUP ELSE dbo.CUSTTABLE.SALESGROUP END AS [Sales Rep],
    dbo.LOGISTICSPOSTALADDRESS.STATE [Customer Region],
    dbo.LOGISTICSPOSTALADDRESS.COUNTY [Customer County],
    dbo.CUSTTABLE.LINEOFBUSINESSID AS [Line Of Business],
    a.DISPLAYVALUE AS [Site/Location],
    dbo.CUSTPACKINGSLIPTRANS.PACKINGSLIPID AS [Delivery Ref],
    dbo.LOGISTICSPOSTALADDRESS.COUNTRYREGIONID,
    CONVERT(varchar(12), dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE, 111) AS [Delivery Date],
    dbo.LOGISTICSPOSTALADDRESS.ADDRESS AS [Delivery Address],
    dbo.CUSTPACKINGSLIPTRANS.VALUEMST AS [Delivery Value (CON)],
    CONVERT(varchar(12), dbo.SALESTABLE.RECEIPTDATEREQUESTED, 111) AS [Requested Delivery Date],
    dbo.SALESTABLE.SALESID AS [Order Ref],
    CASE dbo.SALESTABLE.SALESSTATUS WHEN '0' THEN 'None' WHEN '1' THEN 'Open Order' WHEN '2' THEN 'Delivered' WHEN '3' THEN 'Invoiced' WHEN '4' THEN 'Canceled' END AS [Sales Status],
    CASE dbo.SALESTABLE.SALESTYPE WHEN '0' THEN 'Journal' WHEN '1' THEN 'Quotation' WHEN '2' THEN 'Subscription' WHEN '3' THEN 'Sales Order' WHEN '4' THEN 'Returned Item' WHEN '5' THEN 'Blanket Order' WHEN '6' THEN 'Item Requirements' WHEN '7' THEN 'Undefined' END AS [Sales Type],
    CASE dbo.SALESTABLE.AG_SALESLOCATION WHEN '0' THEN 'None' WHEN '1' THEN 'OR_DGN' WHEN '2' THEN 'OR_FMT' WHEN '3' THEN 'OR_TME' WHEN '4' THEN 'OR_OMA' WHEN '5' THEN 'DSP_DGN' WHEN '6' THEN 'DSP_FMT' WHEN '7' THEN 'DSP_TME' WHEN '8' THEN 'DSP_OMA' WHEN '9' THEN 'DSP_BEL' WHEN '10' THEN 'DSP_CDF' WHEN '11' THEN 'DSP_BGY' WHEN '12' THEN 'Credit Control' WHEN '13' THEN 'Internal Sales' WHEN '14' THEN 'CP_FMT' WHEN '15' THEN 'GBSales' END AS [Sales Location],
    dbo.SALESTABLE.PURCHORDERFORMNUM AS [Customer Requisition],
    dbo.SALESLINE.LINEDISC AS [Line Disc],
    dbo.SALESLINE.LINEPERCENT AS [Line Percent],
    dbo.SALESLINE.PRICEGROUPID AS [Price Group],
    dbo.INVENTDIM.INVENTLOCATIONID AS Warehouse,
    dbo.DIRPARTYTABLE.NAMEALIAS AS [Search Name],
    dbo.CUSTPACKINGSLIPJOUR.LORRYID AS [Lorry ID],
    dbo.CUSTPACKINGSLIPJOUR.LORRYREGNO AS [Lorry Reg],
    dbo.CUSTPACKINGSLIPJOUR.LORRYDRIVER AS [Lorry Driver],
    CASE dbo.SALESLINE.BLOCKED WHEN '0' THEN 'No' WHEN '1' THEN 'Yes' END AS [Stopped?],
    dbo.CUSTPACKINGSLIPTRANS.QTY AS [Qty Delivered],
    dbo.SALESLINE.SALESPRICE AS [Unit Price],
    dbo.CUSTPACKINGSLIPJOUR.CREATEDBY AS [SDN Creator],
    MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS Month,
    YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS Year,
    DATEPART(week, dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) AS WeekNo,
    CASE MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) WHEN '1' THEN '10' WHEN '2' THEN '11' WHEN '3' THEN '12' WHEN '4' THEN '1' WHEN '5' THEN '2' WHEN '6' THEN '3' WHEN '7' THEN '4' WHEN '8' THEN '5' WHEN '9' THEN '6' WHEN '10' THEN '7' WHEN '11' THEN '8' WHEN '12' THEN '9' END AS [Fin Period], CASE WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) <= '3' THEN CONVERT(VARCHAR(10), (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) - 1)) + '/' + CONVERT(VARCHAR(10), YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE)) WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) >= '4' THEN CONVERT(VARCHAR(10), YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE)) + '/' + CONVERT(VARCHAR(10), (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) + 1)) END AS [Fin Year],
    CASE WHEN dbo.custpackingsliptrans.salesunit = '100' THEN dbo.CUSTPACKINGSLIPTRANS.SALESUNIT * dbo.CUSTPACKINGSLIPTRANS.QTY WHEN dbo.custpackingsliptrans.salesunit = '1000' THEN dbo.CUSTPACKINGSLIPTRANS.SALESUNIT * dbo.CUSTPACKINGSLIPTRANS.QTY ELSE dbo.CUSTPACKINGSLIPTRANS.QTY END AS [No of Units],
    CASE dbo.INVENTITEMGROUPITEM.ITEMGROUPID WHEN 'Mortar' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Sand' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Decorative Gravel' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Crushed Aggregates' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Lintels' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 WHEN 'TBeams' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 WHEN 'Aggregates' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) WHEN 'Lime' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY * dbo.UNITOFMEASURECONVERSION.FACTOR) WHEN 'Readymix' THEN (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY) / 1000 ELSE (dbo.INVENTTABLE.NETWEIGHT * dbo.CUSTPACKINGSLIPTRANS.QTY * dbo.UNITOFMEASURECONVERSION.FACTOR) / 1000 END AS Tonnage,
    dbo.INVENTTABLE.NETWEIGHT AS [Net Weight],
    dbo.INVENTTABLE.PRODCOSTA,
    dbo.INVENTTABLE.PRODCOSTB,
    dbo.INVENTTABLE.PRODCOSTC,
    dbo.INVENTTABLE.PRODCOSTD,
    dbo.INVENTTABLE.PRODCOSTE,
    dbo.INVENTTABLE.PRODCOSTF,
    dbo.INVENTTABLE.PRODCOSTG,
    dbo.INVENTTABLE.PRODCOSTH,
    dbo.INVENTTABLE.QTYPERBALE,
    dbo.INVENTTABLE.M2PERBALE,
    dbo.SALESTABLE.SALESTYPE,
    dbo.SALESTABLE.DLVMODE AS [Delivery Mode],
    CONVERT(varchar(12), dbo.SALESTABLE.SHIPPINGDATECONFIRMED, 111) AS [Shipping Date Confirmed],
    CONVERT(varchar(12), dbo.SALESTABLE.CREATEDDATETIME, 111) AS [Created Date],
    dbo.SALESLINE.CUSTGROUP AS [Cust Group],
    dbo.INVENTTABLE.MADETOORDER AS [Made To Order]
    FROM dbo.CUSTPACKINGSLIPTRANS INNER JOIN
    dbo.CUSTPACKINGSLIPJOUR ON dbo.CUSTPACKINGSLIPTRANS.PACKINGSLIPID = dbo.CUSTPACKINGSLIPJOUR.PACKINGSLIPID INNER JOIN
    dbo.SALESLINE ON dbo.CUSTPACKINGSLIPJOUR.SALESID = dbo.SALESLINE.SALESID AND
    dbo.CUSTPACKINGSLIPTRANS.INVENTTRANSID = dbo.SALESLINE.INVENTTRANSID INNER JOIN
    dbo.INVENTTABLE ON dbo.CUSTPACKINGSLIPTRANS.ITEMID = dbo.INVENTTABLE.ITEMID INNER JOIN
    dbo.INVENTITEMGROUPITEM ON dbo.INVENTTABLE.ITEMID = dbo.INVENTITEMGROUPITEM.ITEMID INNER JOIN
    dbo.INVENTITEMGROUP ON dbo.INVENTITEMGROUPITEM.ITEMGROUPID = dbo.INVENTITEMGROUP.ITEMGROUPID INNER JOIN
    dbo.INVENTDIM ON dbo.SALESLINE.INVENTDIMID = dbo.INVENTDIM.INVENTDIMID INNER JOIN
    dbo.CUSTTABLE ON dbo.CUSTPACKINGSLIPJOUR.ORDERACCOUNT = dbo.CUSTTABLE.ACCOUNTNUM INNER JOIN
    dbo.DIRPARTYTABLE ON dbo.CUSTTABLE.PARTY = dbo.DIRPARTYTABLE.RECID INNER JOIN
    dbo.LOGISTICSPOSTALADDRESS ON dbo.DIRPARTYTABLE.PRIMARYADDRESSLOCATION = dbo.LOGISTICSPOSTALADDRESS.LOCATION INNER JOIN
    dbo.SALESTABLE ON dbo.SALESLINE.SALESID = dbo.SALESTABLE.SALESID INNER JOIN
    dbo.DIRPERSONNAME ON dbo.SALESTABLE.WORKERSALESTAKER = dbo.DIRPERSONNAME.RECID INNER JOIN
    dbo.ECORESPRODUCT ON dbo.CUSTPACKINGSLIPTRANS.ITEMID = dbo.ECORESPRODUCT.SEARCHNAME
    AND dbo.INVENTTABLE.ITEMID = dbo.ECORESPRODUCT.DISPLAYPRODUCTNUMBER LEFT OUTER JOIN
    dbo.UNITOFMEASURECONVERSION ON dbo.ECORESPRODUCT.RECID = dbo.UNITOFMEASURECONVERSION.PRODUCT LEFT OUTER JOIN
    dbo.UNITOFMEASURE ON dbo.UNITOFMEASURECONVERSION.TOUNITOFMEASURE = dbo.UNITOFMEASURE.RECID INNER JOIN
    dbo.DEFAULTDIMENSIONVIEW a ON dbo.CUSTPACKINGSLIPTRANS.DEFAULTDIMENSION = a.DEFAULTDIMENSION AND a.NAME = 'Department' LEFT OUTER JOIN
    dbo.DEFAULTDIMENSIONVIEW b ON dbo.INVENTTABLE.DEFAULTDIMENSION = b.DEFAULTDIMENSION AND b.NAME = 'Center' INNER JOIN
    dbo.DIMENSIONFINANCIALTAG ON b.ENTITYINSTANCE = dbo.DIMENSIONFINANCIALTAG.RECID
    WHERE (dbo.CUSTPACKINGSLIPTRANS.DATAAREAID = 'agl') AND
    (dbo.CUSTPACKINGSLIPJOUR.DATAAREAID = 'agl') AND
    (dbo.SALESLINE.DATAAREAID = 'agl') AND
    (dbo.INVENTTABLE.DATAAREAID = 'vuk') AND
    (dbo.INVENTDIM.DATAAREAID = 'agl') AND
    (dbo.CUSTTABLE.DATAAREAID = 'agl') AND
    (dbo.SALESTABLE.DATAAREAID = 'agl') AND
    (CASE WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) <= '3' THEN (YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) - 1)
    WHEN MONTH(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) >= '4' THEN YEAR(dbo.CUSTPACKINGSLIPTRANS.DELIVERYDATE) END = 2014)
    Try to minimize joins using intermediary tables, also you can consider limiting data based on date ranges and codes (DATAAREAID) before joining with other tables.

Maybe you are looking for

  • Doubt I purchase another Insignia

    I purchased an Insignia television with DVD player built into the side. I am really wishing I would of bought a different brand. For starters the volume stinks! I can have it turned all the way up and still need it louder. I have never had surround s

  • ESATA connection for Mac Mini?

    Is there any way I can connect an external HD with an eSATA connection to my Mac Mini? (2.7 GHz Intel Core i7, OS 10.8.1, 16 GB 1333 MHz DDR3) Thanks.

  • Stolen RAM cards

    So I loaned my Power Mac G5 out to my old roommate for video-editing since I have a new(er) MacBook Pro I've been using. When I got it back, it was missing two 1gb cards with the slots still open, not to mention the superdrive is now clicking when wa

  • Can Endpoint 2012 be used on Windows Server 2008 R2?

    I have never used this product before.  I just need to protect one Microsoft Window Server running 2008 R2 Enterprise.  I don't need to install the infrastructure or manager.  Is this possible? Thanks!

  • I have a web page that uses a library item( !-- #BeginLibraryItem "/lib/topnav_main.lbi" -- ) . I

    I have a web page that uses a library item( <!-- #BeginLibraryItem "/lib/topnav_main.lbi" --> ) . I have made a change to topnav_main.lbi but don't know how to get it updated to the web page .  It is a heading and is used in many places. Can you help