Rewrite SQL query to improve performance

Hello,
The below queries are very time consuming.Could you please suggest how to improve performance for these 2 queries:
QUERY1:
SELECT avbeln aposnr aauart avkorg avtweg aspart
avkbur akunnr bmatnr bkwmeng b~vrkme
bnetwr bwerks blgort bvstel babgru berdat b~ernam
cfaksk cktext cvdatu czzbrsch ckvgr1 caugru
INTO CORRESPONDING FIELDS OF TABLE g_t_sodata
            FROM vapma AS a INNER JOIN vbap AS b ON
            avbeln = bvbeln AND aposnr = bposnr
            INNER JOIN vbak AS c ON avbeln = cvbeln
              WHERE a~vkorg IN so_vkorg
              AND a~vtweg IN so_vtweg
              AND a~vkbur IN so_vkbur
              AND a~auart IN so_auart
              AND a~vbeln IN so_vbeln
              AND b~abgru IN so_abgru
              AND c~faksk IN so_faksk
              AND ( b~erdat GT g_f_zenkai_date OR
        ( berdat EQ g_f_zenkai_date AND berzet GE g_f_zenkai_time ) )
        AND ( b~erdat LT g_f_kaisi_date  OR
         ( berdat EQ g_f_kaisi_date  AND berzet LT g_f_kaisi_time ) ).
QUERY2:
SELECT avbeln aposnr aauart avkorg avtweg aspart
        avkbur akunnr bmatnr bkwmeng  b~vrkme
        b~netwr
        bwerks blgort bvstel babgru berdat bernam
        cfaksk cktext cvdatu czzbrsch ckvgr1 caugru
        INTO CORRESPONDING FIELDS OF TABLE g_t_sodata
       FROM vapma AS a INNER JOIN vbap AS b ON
       avbeln = bvbeln AND aposnr = bposnr
       INNER JOIN vbak AS c ON avbeln = cvbeln
         WHERE a~vkorg IN so_vkorg
         AND a~vtweg IN so_vtweg
         AND a~vkbur IN so_vkbur
         AND a~auart IN so_auart
         AND a~vbeln IN so_vbeln
         AND b~abgru IN so_abgru
         AND c~faksk IN so_faksk.

Questions like this a one of the favorites here in this forum.
I guess that the statements are o.k.
The problem is the usage!  There are so many Ranges, if they are filled then some index should support it. If no range is filled then it is usually slow, you can not do anything.
You must find out, which are actually used and under which conditions it is slow and when it is o.k.
Ask again, when you can provide the actual cases.
Use SQL trace to check the performance:
SQL trace:
The SQL Trace (ST05) – Quick and Easy
I know the probabilty is high, that you will ignore this recommendation and you will points to the
'Use FOR ALL ENTRIES' recommendations' ... but then I can not help you.
Siegfried

Similar Messages

  • Rewrite update query to improve performance - sql attached

    Hi ,
    The following query(pasted below) is taking 4 hours to compelete, table ef is having 10 crore records, and I have 3 binary indexes defined on ef on columns as_at_date, cc and fid (these are individual indexes), just want to know if there is any better way to write the query?
    Many thanks
    Rahul
    SQL :
    update ef emp
    set emp.b2r = (
    select e.b2r
    from ef e
    where e.as_at_date  = (select max(as_at_date) from ef where b2r is not null)
    and e.b2r is not null
    and emp.fid = e.fid
    and emp.cc = e.cc
    where substr(emp.as_at_date,1,6) >= (select substr(max(fk_reporting_date_id),1,6) from f_c_f)
    and exists (
    select e.b2r
    from ef e
    where e.as_at_date = (select max(as_at_date) from ef where b2r is not null)
    and e.b2r is not null
    and emp.fid=e.fid
    and emp.cc=e.cc

    > which column uniquely identifies every row : UNKNOW to me(really sorry)
    This is a very critical piece of information. UNKNOWN is a very wrong answer. You need to know such things before keeping your hands on keyboard.
    Any way based on your update statement you can convert it into merge statement like this
    merge into ef a
    using (
             select b2r
                  , fid
                  , cc
               from (
                       select b2r
                            , fid
                            , cc
                            , row_number() over
                                             partition by fid
                                                        , cc
                                                 order by decode(b2r, null, null, as_at_date)
                                                     desc nulls last
                                           ) rno
                         from ef
              where rno = 1
          ) b
       on (
              a.fid = b.fid and
              a.cc  = b.cc  and
              ubstr(a.as_at_date,1,6) >= (select substr(max(fk_reporting_date_id),1,6) from f_c_f)
    when matched then
    update set a.b2r = b.b2r;
    Note: The code is untested
    This scans your EF table lesser number of time. As you are in 11g you can try using DBMS_PARALLEL_EXECUTE to speed up your SQL.

  • How can we rewrite this query for better performance

    Hi All,
    The below query is taking more time to run. Any ideas how to improve the performance by rewriting the query using NOT EXITS or any other way...
    Help Appreciated.
    /* Formatted on 2012/04/25 18:00 (Formatter Plus v4.8.8) */
    SELECT vendor_id
    FROM po_vendors
    WHERE end_date_active IS NULL
    AND enabled_flag = 'Y'
    and vendor_id NOT IN ( /* Formatted on 2012/04/25 18:25 (Formatter Plus v4.8.8) */
    SELECT vendor_id
    FROM po_headers_all
    WHERE TO_DATE (creation_date) BETWEEN TO_DATE (SYSDATE - 365)
    AND TO_DATE (SYSDATE))
    Thanks

    Try this one :
    This will help you for partial fetching of data
    SELECT /*+ first_rows(50) no_cpu_costing */
    vendor_id
    FROM po_vendors
    WHERE end_date_active IS NULL
    AND enabled_flag = 'Y'
    AND vendor_id NOT IN (
    SELECT vendor_id
    FROM po_headers_all
    WHERE TO_DATE (creation_date) BETWEEN TO_DATE (SYSDATE - 365)
    AND TO_DATE (SYSDATE))
    overall your query is also fine, because, the in this query the subquery always contain less data compare to main query.

  • Rewrite sql query

    Hello,
    I need to rewrite this SQL query to give the same result, but in more resorcefull manner.
    Probably using aggregation, but I am not sure.
    Can somebody give me a head start.
    desc resource_bundles
    Name          Null     Type               
    LOCALE        NOT NULL CHAR(5)            
    BUNDLE_NAME   NOT NULL VARCHAR2(32)       
    RESOURCE_NAME NOT NULL VARCHAR2(64)       
    VALUE_STRING           VARCHAR2(2048 CHAR)
    select a.bundle_name,a.resource_name, a.value_string as Czech,(select b.value_string
                                             from resource_bundles b
                                             where b.bundle_name = a.bundle_name
                                             and b.resource_name = a.resource_name
                                             and b.locale = 'en_US'
                                            )as English,
                                             (select c.value_string
                                             from resource_bundles c
                                             where c.bundle_name = a.bundle_name
                                             and c.resource_name = a.resource_name
                                             and c.locale = 'ru_RU'
                                             ) as Russian,
                                             (select d.value_string
                                             from resource_bundles d
                                             where d.bundle_name = a.bundle_name
                                             and d.resource_name = a.resource_name
                                             and d.locale = 'it_IT'
                                            ) as Italian
    from resource_bundles a
    where a.locale = 'cs_CZ';Thank you
    Edited by: BluShadow on 15-Apr-2011 12:20
    added {noformat}{noformat} tags                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    It is always helpful to provide the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
    Also see the third post in this thread:
    {thread:id=2174552}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • SCOM SQL query killing instance performance

    Hi!
    Since a few day, a new query running against our SCOM datawarehouse db is killing the performance of the SQL instance. The query run 1'000'000 times per hour for a total of 100'000'000 logical read per hour, and this continuously. The query is part of the
    following Procedure: OperationsManagerDW.dbo.fn_BuildInstancePropertyDelta
    Any idea what's wrong ?
    What could trigger this new behavior ? 
    Rgds
    /Chris
    Waiting on statement:
    RETURN
       SELECT 1 AS Tag ,
          NULL AS Parent ,
          ISNULL(S1.PropertyGuid, S2.PropertyGuid) AS [Property!1!Guid] ,
          S1.PropertyValue AS [Property!1!NewValue!ELEMENT] ,
          S2.PropertyValue AS [Property!1!OldValue!ELEMENT]
       FROM
          SELECT PropertyGuid = Set1.PropertyXml.value('@Guid' ,'nvarchar(256)') ,
             PropertyValue = Set1.PropertyXml.value('.' ,'nvarchar(max)')
          FROM @PropertyXml1.nodes('Root/Property') AS Set1(PropertyXml)
          ) AS S1
       FULL JOIN
          SELECT PropertyGuid = Set1.PropertyXml.value('@Guid' ,'nvarchar(256)') ,
             PropertyValue = Set1.PropertyXml.value('.' ,'nvarchar(max)')
          FROM @PropertyXml2.nodes('Root/Property') AS Set1(PropertyXml)
          ) AS S2
       ON (S1.PropertyGuid = S2.PropertyGuid)
       WHERE (S1.PropertyValue <> S2.PropertyValue)
       OR ( (ISNULL(S1.PropertyValue, S2.PropertyValue) IS NOT NULL)
      AND ((S1.PropertyValue IS NULL)
       OR (S2.PropertyValue IS NULL)) ) FOR XML EXPLICIT

    Hallo,
    We open a ticket to Microsoft Support.
    In the SCOM application logs, this huge SQL cpu activity correlates with an error 31553, Violation of unique key constraint.
    We get the information that if the following query return some rows, it means you are hitting the same issue and you should better open a ticket to get information how to fix the problem.
    select
    * from ManagedEntityStage mes
    inner
    join ManagedEntity me on mes.ManagedEntityGuid
    = me.ManagedEntityGuid
    inner
    join ManagedEntityProperty mep
    on me.ManagedEntityRowId
    = mep.ManagedEntityRowId
    where mep.FromDateTime
    = mes.ChangeDateTime
    order
    by mep.ManagedEntityRowId
    Rgds
    /Chris

  • Performance Problem with SQL Query

    Hi
    I have a SQL Query (say, SSS) which runs quite fast when I run it from TOAD.
    But when the same query is being used as
    INSERT INTO <table> VALUES <SSS>;
    It is taking hours to complete.
    The Original Query(OSQ) was changed to this SQL query(SSS) for Performance improvement.
    The Cost has also improved quite a lot from OSQ to SSS. But when SSS runs from inside a procedure it is taking the same long hours as OSQ used to take.
    Please help ASAP as it needs to get fixed.
    Thanks
    Arnab

    SELECT SRM.ID PROJECT_ID,
    SRM.UNIQUE_NAME PROJECT_CODE,
    ODFP.GS_FINANCE_PROJ_CODE,
    ODFP.GS_PRODUCT_CODE,
    ODFP.GS_CUSTOMER,
    ODFP.GS_LEGAL_ENT_REF,
    ODF_PRJ_TYPE.NAME GS_PROJ_TYPE,
    ODF_SRC_SYS.NAME GS_SOURCE_SYSTEM,
    RESM.FIRST_NAME||' '||RESM.LAST_NAME GS_PROJECT_MANAGER,
    ODFP.GS_LEG_PROJ_NUM,
    ODFP.GS_SUPP_DOC ,
    ODFP.GS_REQUEST_ID ,
    ODFP.GS_CONTRACT ,
    ODFP.GS_SIEBEL_REF,
    DECODE(budg.ODF_PARENT_ID,NULL,PRJP.bdgt_cst_total, budg.lab_budg)LAB_BDGT,
    DECODE(budg.ODF_PARENT_ID,NULL,0,budg.nli_budg)NLI_BDGT,
    (DECODE(budg.ODF_PARENT_ID,NULL,PRJP.bdgt_cst_total, budg.lab_budg))+(DECODE(budg.ODF_PARENT_ID,NULL,0,budg.nli_budg)) sum_lab_nonlab_budg,
    frct.LABOUR,
    frct.NON_LABOUR,
    frct.LABOUR+frct.NON_LABOUR FORCAST_TOT_SUM,
    gfr.code GFR_CODE,
    odfp.gs_rev_recognition,
    rev_rec.NAME gs_rev_recognition,
    DECODE(odfp.gs_prevent_reqtxn,1,'YES','0','NO','NO'),
    GS_PROGTYPE.NAME,
    COMM_APPR.UNIQUE_NAME COMM_APPROVER_EIN,
    COMM_APPR.FIRST_NAME||' '||COMM_APPR.LAST_NAME COMM_APPROVER_NAME,
    PR_APPR.UNIQUE_NAME PR_APPROVER_EIN,
    PR_APPR.FIRST_NAME||' '||PR_APPR.LAST_NAME PR_APPROVER_NAME,
    ODFP.GS_BILL_BUD,
    frct.FRCST_REVENUE TOTAL_FRC_REVENUE,
    actuals.LABOUR_ACTUALS,
    actuals.NL_ACTUALS,
    -- get_wip_totalcost(prjp.prid,'L') LABOUR_ACTUALS,
    -- get_wip_totalcost(prjp.prid,'M') NL_ACTUALS,
    ODFP.GS_ASS_PRODUCT_CODE,
    PROJ_TEMPLATE.ID GS_PROJ_TEMPLATE_ID,
    PROJ_TEMPLATE.UNIQUE_NAME GS_PROJ_TEMPLATE_CODE,
    PROJ_TEMPLATE.name GS_PROJ_TEMPLATE_NAME,
    DECODE( NVL(ODFP.GS_FIN_TEMPLATE,0) ,0,'NO',1,'YES') GS_FIN_TEMPLATE,
    ODF_PRJ_TYPE.LOOKUP_CODE GS_PROJ_TYPE
    FROM PROJECTS SRM,
    J_PROJECTS PRJP,
    A_PROJECT ODFP,
    RESOURCES RESM,
    s_gfr gfr,
    RESOURCES PROJ_ACCT,
    RESOURCES COMM_APPR,
    RESOURCES PR_APPR,
    (SELECT CAP.NAME
    ,LOOKUP.LOOKUP_CODE
    FROM S_NLS CAP,
    N_LOOKUPS LOOKUP
    WHERE LOOKUP_TYPE ='GS_PROJECT_TYPE'
    AND LOOKUP.ID =CAP.PK_ID
    AND CAP.LANGUAGE_CODE='en'
    AND CAP.TABLE_NAME = 'CMN_LOOKUPS') ODF_PRJ_TYPE,
    (SELECT CAP.NAME
    ,LOOKUP.LOOKUP_CODE
    FROM S_NLS CAP,
    N_LOOKUPS LOOKUP
    WHERE LOOKUP_TYPE ='GS_SOURCE_SYSTEM'
    AND LOOKUP.ID =CAP.PK_ID
    AND CAP.LANGUAGE_CODE='en'
    AND CAP.TABLE_NAME = 'CMN_LOOKUPS') ODF_SRC_SYS,
    (SELECT CAP.NAME
    ,LOOKUP.LOOKUP_CODE
    FROM S_NLS CAP,
    N_LOOKUPS LOOKUP
    WHERE LOOKUP_TYPE ='GS_PROG_TYPE'
    AND LOOKUP.ID =CAP.PK_ID
    AND CAP.LANGUAGE_CODE='en'
    AND CAP.TABLE_NAME = 'CMN_LOOKUPS')GS_PROGTYPE,
    (SELECT odf_parent_id
    ,SUM(gs_lab_budg) lab_budg
    ,SUM(gs_nl_budg) nli_budg
    FROM T_CHANGES
    WHERE gs_status='APPR'
    GROUP BY odf_parent_id) budg,
    (SELECT CAP.NAME
    ,LOOKUP.LOOKUP_CODE
    FROM S_NLS CAP,
    N_LOOKUPS LOOKUP
    WHERE LOOKUP_TYPE ='GS_REV_RECOGNITION'
    AND LOOKUP.ID = CAP.PK_ID
    AND CAP.LANGUAGE_CODE='en'
    AND CAP.TABLE_NAME = 'CMN_LOOKUPS') rev_rec,
    (SELECT FRCP1.project_id,
    NVL(SUM(CASE WHEN srmr.resource_type=0 THEN for_val.cost ELSE NULL END),0) AS LABOUR,
    NVL(SUM(CASE WHEN srmr.resource_type <> 0 THEN for_val.cost ELSE NULL END),0) AS NON_LABOUR,
    NVL(SUM(for_val.revenue),0) AS FRCST_REVENUE
    FROM T_PROPERTIES FRCP1,
    T_DETAILS FOR_DET,
    RESOURCES SRMR,
    T_VALUES FOR_VAL
    WHERE (FRCP1.project_id, revision) IN (SELECT project_id, MAX(revision)
    FROM T_PROPERTIES FRCP
    WHERE FRCP.status=2
    AND FRCP.PERIOD_TYPE='SEMI_MONTHLY'
    GROUP BY project_id)
    AND FRCP1.PERIOD_TYPE='SEMI_MONTHLY'
    AND FOR_DET.forecast_id=frcp1.id
    AND SRMR.id(+)=FOR_DET.detail_id
    AND FOR_VAL.currency_type='BILLING'
    AND FOR_VAL.forecast_details_id=FOR_DET.ID
    GROUP BY FRCP1.project_id) frct,
    (SELECT srmp.id
    ,NVL(SUM(CASE WHEN wip.transtype='L' THEN WIPVAL.TOTALCOST ELSE NULL END),0) AS LABOUR_ACTUALS
    ,NVL(SUM(CASE WHEN wip.transtype='M' THEN WIPVAL.TOTALCOST ELSE NULL END),0) AS NL_ACTUALS
    FROM A_WIP WIP
    ,om_periods biz
    ,P_VALUES WIPVAL
    ,PROJECTS SRMP
    ,A_PROJECT ODF
    WHERE biz.period_type ='SEMI_MONTHLY'
    AND TRUNC(wip.TRANSDATE) BETWEEN biz.start_date AND biz.end_date
    AND WIP.TRANSNO=WIPVAL.TRANSNO
    AND WIPVAL.CURRENCY_TYPE='BILLING'
    AND SRMP.UNIQUE_NAME=WIP.PROJECT_CODE
    AND SRMP.ID=ODF.ID
    AND UPPER(ODF.partition_code)='GLOBAL'
    AND UPPER(WIP.external_id) <> 'SPREADSHEET'
    GROUP BY srmp.id) actuals,
    RESOURCES BUD_HOLDER,
    PROJECTS PROJ_TEMPLATE
    WHERE SRM.ID = PRJP.PRID
    AND ODFP.ID=PRJP.PRID
    AND ODFP.PARTITION_CODE='GLOBAL'
    AND RESM.id(+)=prjp.manager_id
    AND ODFP.GS_PROJECT_TYPE = ODF_PRJ_TYPE.LOOKUP_CODE(+)
    AND ODFP.GS_SOURCE_SYSTEM = ODF_SRC_SYS.LOOKUP_CODE(+)
    AND ODFP.GS_prog_type = GS_PROGTYPE.LOOKUP_CODE(+)
    AND budg.odf_parent_id(+)=SRM.ID
    AND frct.project_id(+) = prjp.prid
    AND ODFP.gs_risk_gfr=gfr.code(+)
    AND ODFP.GS_REV_RECOGNITION=rev_rec.LOOKUP_CODE(+)
    AND ODFP.GS_PROJ_ACCT = PROJ_ACCT.ID(+)
    AND ODFP.GS_COMM_APPR = COMM_APPR.ID(+)
    AND ODFP.GS_PR_APPR = PR_APPR.ID(+)
    AND actuals.id(+) = prjp.prid -- Arnab
    AND ODFP.GS_BUDGET_HOLDER=BUD_HOLDER.ID(+)
    AND ODFP.GS_TEMPLATE_USED=PROJ_TEMPLATE.ID(+)
    The above is OSQ with cost 45000. ... takes 1-1.5 hours through Toad
    SELECT SRM.ID PROJECT_ID,
    SRM.UNIQUE_NAME PROJECT_CODE,
    ODFP.GS_FINANCE_PROJ_CODE,
    ODFP.GS_PRODUCT_CODE,
    ODFP.GS_CUSTOMER,
    ODFP.GS_LEGAL_ENT_REF,
    ODF_PRJ_TYPE.NAME GS_PROJ_TYPE,
    ODF_SRC_SYS.NAME GS_SOURCE_SYSTEM,
    RESM.FIRST_NAME||' '||RESM.LAST_NAME GS_PROJECT_MANAGER,
    ODFP.GS_LEG_PROJ_NUM,
    ODFP.GS_SUPP_DOC ,
    ODFP.GS_REQUEST_ID ,
    ODFP.GS_CONTRACT ,
    ODFP.GS_SIEBEL_REF,
    DECODE(budg.ODF_PARENT_ID,NULL,PRJP.bdgt_cst_total, budg.lab_budg)LAB_BDGT,
    DECODE(budg.ODF_PARENT_ID,NULL,0,budg.nli_budg)NLI_BDGT,
    (DECODE(budg.ODF_PARENT_ID,NULL,PRJP.bdgt_cst_total, budg.lab_budg))+(DECODE(budg.ODF_PARENT_ID,NULL,0,budg.nli_budg)) sum_lab_nonlab_budg,
    frct.LABOUR,
    frct.NON_LABOUR,
    frct.LABOUR+frct.NON_LABOUR FORCAST_TOT_SUM,
    gfr.code GFR_CODE,
    odfp.gs_rev_recognition,
    rev_rec.NAME gs_rev_recognition,
    DECODE(odfp.gs_prevent_reqtxn,1,'YES','0','NO','NO'),
    GS_PROGTYPE.NAME,
    COMM_APPR.UNIQUE_NAME COMM_APPROVER_EIN,
    COMM_APPR.FIRST_NAME||' '||COMM_APPR.LAST_NAME COMM_APPROVER_NAME,
    PR_APPR.UNIQUE_NAME PR_APPROVER_EIN,
    PR_APPR.FIRST_NAME||' '||PR_APPR.LAST_NAME PR_APPROVER_NAME,
    ODFP.GS_BILL_BUD,
    frct.FRCST_REVENUE TOTAL_FRC_REVENUE,
    -- actuals.LABOUR_ACTUALS, -- Arnab
    -- actuals.NL_ACTUALS, -- Arnab
    get_wip_totalcost(prjp.prid,'L') LABOUR_ACTUALS, -- Arnab
    get_wip_totalcost(prjp.prid,'M') NL_ACTUALS, -- Arnab
    ODFP.GS_ASS_PRODUCT_CODE,
    PROJ_TEMPLATE.ID GS_PROJ_TEMPLATE_ID,
    PROJ_TEMPLATE.UNIQUE_NAME GS_PROJ_TEMPLATE_CODE,
    PROJ_TEMPLATE.name GS_PROJ_TEMPLATE_NAME,
    DECODE( NVL(ODFP.GS_FIN_TEMPLATE,0) ,0,'NO',1,'YES') GS_FIN_TEMPLATE,
    ODF_PRJ_TYPE.LOOKUP_CODE GS_PROJ_TYPE
    FROM PROJECTS SRM,
    J_PROJECTS PRJP,
    A_PROJECT ODFP,
    RESOURCES RESM,
    s_gfr gfr,
    RESOURCES PROJ_ACCT,
    RESOURCES COMM_APPR,
    RESOURCES PR_APPR,
    (SELECT CAP.NAME
    ,LOOKUP.LOOKUP_CODE
    FROM S_NLS CAP,
    N_LOOKUPS LOOKUP
    WHERE LOOKUP_TYPE ='GS_PROJECT_TYPE'
    AND LOOKUP.ID =CAP.PK_ID
    AND CAP.LANGUAGE_CODE='en'
    AND CAP.TABLE_NAME = 'CMN_LOOKUPS') ODF_PRJ_TYPE,
    (SELECT CAP.NAME
    ,LOOKUP.LOOKUP_CODE
    FROM S_NLS CAP,
    N_LOOKUPS LOOKUP
    WHERE LOOKUP_TYPE ='GS_SOURCE_SYSTEM'
    AND LOOKUP.ID =CAP.PK_ID
    AND CAP.LANGUAGE_CODE='en'
    AND CAP.TABLE_NAME = 'CMN_LOOKUPS') ODF_SRC_SYS,
    (SELECT CAP.NAME
    ,LOOKUP.LOOKUP_CODE
    FROM S_NLS CAP,
    N_LOOKUPS LOOKUP
    WHERE LOOKUP_TYPE ='GS_PROG_TYPE'
    AND LOOKUP.ID =CAP.PK_ID
    AND CAP.LANGUAGE_CODE='en'
    AND CAP.TABLE_NAME = 'CMN_LOOKUPS')GS_PROGTYPE,
    (SELECT odf_parent_id
    ,SUM(gs_lab_budg) lab_budg
    ,SUM(gs_nl_budg) nli_budg
    FROM T_CHANGES
    WHERE gs_status='APPR'
    GROUP BY odf_parent_id) budg,
    (SELECT CAP.NAME
    ,LOOKUP.LOOKUP_CODE
    FROM S_NLS CAP,
    N_LOOKUPS LOOKUP
    WHERE LOOKUP_TYPE ='GS_REV_RECOGNITION'
    AND LOOKUP.ID = CAP.PK_ID
    AND CAP.LANGUAGE_CODE='en'
    AND CAP.TABLE_NAME = 'CMN_LOOKUPS') rev_rec,
    (SELECT FRCP1.project_id,
    NVL(SUM(CASE WHEN srmr.resource_type=0 THEN for_val.cost ELSE NULL END),0) AS LABOUR,
    NVL(SUM(CASE WHEN srmr.resource_type <> 0 THEN for_val.cost ELSE NULL END),0) AS NON_LABOUR,
    NVL(SUM(for_val.revenue),0) AS FRCST_REVENUE
    FROM T_PROPERTIES FRCP1,
    T_DETAILS FOR_DET,
    RESOURCES SRMR,
    T_VALUES FOR_VAL
    WHERE (FRCP1.project_id, revision) IN (SELECT project_id, MAX(revision)
    FROM T_PROPERTIES FRCP
    WHERE FRCP.status=2
    AND FRCP.PERIOD_TYPE='SEMI_MONTHLY'
    GROUP BY project_id)
    AND FRCP1.PERIOD_TYPE='SEMI_MONTHLY'
    AND FOR_DET.forecast_id=frcp1.id
    AND SRMR.id(+)=FOR_DET.detail_id
    AND FOR_VAL.currency_type='BILLING'
    AND FOR_VAL.forecast_details_id=FOR_DET.ID
    GROUP BY FRCP1.project_id) frct,
    /* (SELECT srmp.id
    ,NVL(SUM(CASE WHEN wip.transtype='L' THEN WIPVAL.TOTALCOST ELSE NULL END),0) AS LABOUR_ACTUALS
    ,NVL(SUM(CASE WHEN wip.transtype='M' THEN WIPVAL.TOTALCOST ELSE NULL END),0) AS NL_ACTUALS
    FROM A_WIP WIP
    ,om_periods biz
    ,P_VALUES WIPVAL
    ,PROJECTS SRMP
    ,A_PROJECT ODF
    WHERE biz.period_type ='SEMI_MONTHLY'
    AND TRUNC(wip.TRANSDATE) BETWEEN biz.start_date AND biz.end_date
    AND WIP.TRANSNO=WIPVAL.TRANSNO
    AND WIPVAL.CURRENCY_TYPE='BILLING'
    AND SRMP.UNIQUE_NAME=WIP.PROJECT_CODE
    AND SRMP.ID=ODF.ID
    AND UPPER(ODF.partition_code)='GLOBAL'
    AND UPPER(WIP.external_id) <> 'SPREADSHEET'
    GROUP BY srmp.id) actuals, */ -- Arnab
    RESOURCES BUD_HOLDER,
    PROJECTS PROJ_TEMPLATE
    WHERE SRM.ID = PRJP.PRID
    AND ODFP.ID=PRJP.PRID
    AND ODFP.PARTITION_CODE='GLOBAL'
    AND RESM.id(+)=prjp.manager_id
    AND ODFP.GS_PROJECT_TYPE = ODF_PRJ_TYPE.LOOKUP_CODE(+)
    AND ODFP.GS_SOURCE_SYSTEM = ODF_SRC_SYS.LOOKUP_CODE(+)
    AND ODFP.GS_prog_type = GS_PROGTYPE.LOOKUP_CODE(+)
    AND budg.odf_parent_id(+)=SRM.ID
    AND frct.project_id(+) = prjp.prid
    AND ODFP.gs_risk_gfr=gfr.code(+)
    AND ODFP.GS_REV_RECOGNITION=rev_rec.LOOKUP_CODE(+)
    AND ODFP.GS_PROJ_ACCT = PROJ_ACCT.ID(+)
    AND ODFP.GS_COMM_APPR = COMM_APPR.ID(+)
    AND ODFP.GS_PR_APPR = PR_APPR.ID(+)
    AND     actuals.id(+) = prjp.prid  Arnab
    AND ODFP.GS_BUDGET_HOLDER=BUD_HOLDER.ID(+)
    AND ODFP.GS_TEMPLATE_USED=PROJ_TEMPLATE.ID(+)
    This one in SSS where "-- Arnab " are only changes .....
    The cost of this 7000.....finishes in 1 - 1.5 min in Toad
    This is used as INSERT INTO TABLE <Select Query> ... this was taking 1.5 Hours to run.
    It was changed using BULK COLLECT - still its taking around 1.5 hours to run...
    Thanks
    Arnab

  • Improving performance while adding groups

    Hello,
    I've been monitoring my crystal reports from a week or so and the report performance is going for a toss. I would like to narrate this in little detail. I have created 3 groups to select dynamic parameters and each group has a formula for itself. In my parameters I have added one parameter with 7 entities (which is hard coded), now a user can select any 3 entity out of those seven when initiallly refreshing the document, each of the parameter entity is bundeled in a conditional formula (mentioned under formula fields) for each entity. The user may select any entity and may get the respective data for that entity.
    For all this i have created 3 groups and same formula is pasted under all the 3 groups. I have then made the formula group to be selected under Group expert. The report works fine and yields me correct data. However, during the grouping of the formula's crystal selects all the database tables from the database field as these tables are mentioned under the group formula. Agreed all fine.
    But when I run the report the "Show SQL query" selects all the database tables under Select clause which should not be the case. Due to this even if i have selected an entity which has got only 48 to 50 records, crystal tends to select all the 16,56,053 records from the database fields which is hampering the crystal performance big time. When I run the same query in SQL it retrives the data in just 8 seconds but as crystal selecting all the records gives me data after 90 seconds which is frustrating for the user.
    Please suggest me a workaround for this. Please help.
    Thank you.

    Hi,
    I suspect the problem isn't necessarily just your grouping but with your Record Selection Formula as well.  If you do not see a complete Where clause is because your Record Selection Formula is too complicated for Crystal to translate to SQL. 
    The same would be said for your grouping.  There are two suggestions I can offer: 
    1)  Instead of linking the tables in Crystal, use a SQL Command and generate your query in SQL directly.  You can use parameters and at the very least, get a working WHERE clause. 
    2)  Create a Stored Procedure or view that can use the logic you need to retrieve the records. 
    At the very least you want to be able to streamline the query to improve performance.  Grouping may not be possible but my guess it's more with the Selection formula than the grouping.
    Good luck,
    Brian

  • Please help to modifiy this query for better performance

    Please help to rewrite this query for better performance. This is taking long time to execute.
    Table t_t_bil_bil_cycle_change contains 1200000 rows and table t_acctnumberTab countains  200000 rows.
    I have created index on ACCOUNT_ID
    Query is shown below
    update rbabu.t_t_bil_bil_cycle_change a
       set account_number =
           ( select distinct b.account_number
             from rbabu.t_acctnumberTab b
             where a.account_id = b.account_id
    Table structure  is shown below
    SQL> DESC t_acctnumberTab;
    Name           Type         Nullable Default Comments
    ACCOUNT_ID     NUMBER(10)                            
    ACCOUNT_NUMBER VARCHAR2(24)
    SQL> DESC t_t_bil_bil_cycle_change;
    Name                    Type         Nullable Default Comments
    ACCOUNT_ID              NUMBER(10)                            
    ACCOUNT_NUMBER          VARCHAR2(24) Y    

    Ishan's solution is good. I would avoid updating rows which already have the right value - it's a waste of time.
    You should have a UNIQUE or PRIMARY KEY constraint on t_acctnumberTab.account_id
    merge rbabu.t_t_bil_bil_cycle_change a
    using
          ( select distinct account_number, account_id
      from  rbabu.t_acctnumberTab
          ) t
    on    ( a.account_id = b.account_id
           and decode(a.account_number, b.account_number, 0, 1) = 1
    when matched then
      update set a.account_number = b.account_number

  • Need SQl Query tune

    Hi,
    This is a part of the procedure which is veryyy slow.. Need some suggestions for the below Query to improve performance. The explain plan and all will be correct in PRODUCTION DB.. In that system, I cant have the explain plan to be copied here. So need suggestions by the Query.
    Here PB,PBD and PBD1 are very huge tables..
    I am unable to paste the Query.. Please help me
    Thanks in advance..

    My car is broken, but I cannot produce it for repairs.
    Not sure of your expectations, but this isn't a way where volunteers have been provided any tiny piece of information to suggest any tuning advice.
    Please read the linked thread HOW TO: Post a SQL statement tuning request - template posting and post with mentioned information.

  • Need help in improving the performance for the sql query

    Thanks in advance for helping me.
    I was trying to improve the performance of the below query. I tried the following methods used merge instead of update, used bulk collect / Forall update, used ordered hint, created a temp table and upadated the target table using the same. The methods which I used did not improve any performance. The data count which is updated in the target table is 2 million records and the target table has 15 million records.
    Any suggestions or solutions for improving performance are appreciated
    SQL query:
    update targettable tt
    set mnop = 'G',
    where ( x,y,z ) in
    select a.x, a.y,a.z
    from table1 a
    where (a.x, a.y,a.z) not in (
    select b.x,b.y,b.z
    from table2 b
    where 'O' = b.defg
    and mnop = 'P'
    and hijkl = 'UVW';

    987981 wrote:
    I was trying to improve the performance of the below query. I tried the following methods used merge instead of update, used bulk collect / Forall update, used ordered hint, created a temp table and upadated the target table using the same. The methods which I used did not improve any performance. And that meant what? Surely if you spend all that time and effort to try various approaches, it should mean something? Failures are as important teachers as successes. You need to learn from failures too. :-)
    The data count which is updated in the target table is 2 million records and the target table has 15 million records.Tables have rows btw, not records. Database people tend to get upset when rows are called records, as records exist in files and a database is not a mere collection of records and files.
    The failure to find a single faster method with the approaches you tried, points to that you do not know what the actual performance problem is. And without knowing the problem, you still went ahead, guns blazing.
    The very first step in dealing with any software engineering problem, is to identify the problem. Seeing the symptoms (slow performance) is still a long way from problem identification.
    Part of identifying the performance problem, is understanding the workload. Just what does the code task the database to do?
    From your comments, it needs to find 2 million rows from 15 million rows. Change these rows. And then write 2 million rows back to disk.
    That is not a small workload. Simple example. Let's say that the 2 million row find is 1ms/row and the 2 million row write is also 1ms/row. This means a 66 minute workload. Due to the number of rows, an increase in time/row either way, will potentially have 2 million fold impact.
    So where is the performance problem? Time spend finding the 2 million rows (where other tables need to be read, indexes used, etc)? Time spend writing the 2 million rows (where triggers and indexes need to be fired and maintained)? Both?

  • What Indexes should be created for improve performance of the sql query

    Hello Admins
    One of my user is facing slow performance issue while running the below query. Can someone, please guide me for the same. I want to know, what indexes should be created to improve the performance of this query. Also what else can be done to achieve the same.
    SQL Query:-
    SELECT UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_NUMBER))),
    CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_NUMBER,
    CGSBI_SHIP_DIST_S_EXTRACT.PO_SHIPMENT_NUMBER,
    CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_SHIP_DIST_NUMBER,
    CGSBI_SHIP_DIST_S_EXTRACT.DISTRIBUTION_DATE,
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_SHIP_DIST_LINE_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PROJECT_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ACCOUNT_DISTRIBUTION_CODE))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ORACLE_ACCOUNT_NUMBER))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.COMPONENT_CODE))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.TRANSACTION_CURRENCY_CODE))),
    CGSBI_SHIP_DIST_S_EXTRACT.ORDER_QUANTITY, UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ORDER_UOM))),
    CGSBI_SHIP_DIST_S_EXTRACT.UNIT_PRICE_TRX_CURRENCY,
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.EXPENSE_TYPE_INDICATOR))),
    CGSBI_SHIP_DIST_S_EXTRACT.SOR_ID,
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_CODE))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_DESC))),
    CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_LEAD_TIME,
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.UNSPSC_CODE))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.BUYER_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.REQUESTOR_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.APPROVER_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SUPPLIER_SITE_ID))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SUPPLIER_GSL_NUMBER))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SHIP_TO_LOCATION_CODE))),
    UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.TASK_ID))),
    (LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_RELEASE_ID)))
    FROM
    CGSBI_SHIP_DIST_S_EXTRACT
    WHERE PO_NUMBER IS NOT NULL;
    I generated the explain plan for this query and found the following:-
    Explain Plan:-
    SQL> explain plan for SELECT UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_NUMBER))),
    2 CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_NUMBER,
    3 CGSBI_SHIP_DIST_S_EXTRACT.PO_SHIPMENT_NUMBER,
    4 CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_SHIP_DIST_NUMBER,
    5 CGSBI_SHIP_DIST_S_EXTRACT.DISTRIBUTION_DATE,
    6 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_SHIP_DIST_LINE_ID))),
    7 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PROJECT_ID))),
    8 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ACCOUNT_DISTRIBUTION_CODE))),
    9 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ORACLE_ACCOUNT_NUMBER))),
    10 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.COMPONENT_CODE))),
    11 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.TRANSACTION_CURRENCY_CODE))),
    12 CGSBI_SHIP_DIST_S_EXTRACT.ORDER_QUANTITY, UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.ORDER_UOM))),
    13 CGSBI_SHIP_DIST_S_EXTRACT.UNIT_PRICE_TRX_CURRENCY,
    14 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.EXPENSE_TYPE_INDICATOR))),
    15 CGSBI_SHIP_DIST_S_EXTRACT.SOR_ID,
    16 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_CODE))),
    17 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_DESC))),
    18 CGSBI_SHIP_DIST_S_EXTRACT.PO_LINE_ITEM_LEAD_TIME,
    19 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.UNSPSC_CODE))),
    20 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.BUYER_ID))),
    21 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.REQUESTOR_ID))),
    22 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.APPROVER_ID))),
    23 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SUPPLIER_SITE_ID))),
    24 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SUPPLIER_GSL_NUMBER))),
    25 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.SHIP_TO_LOCATION_CODE))),
    26 UPPER(LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.TASK_ID))),
    27 (LTRIM(RTRIM(CGSBI_SHIP_DIST_S_EXTRACT.PO_RELEASE_ID)))
    28 FROM
    29 CGSBI_SHIP_DIST_S_EXTRACT
    30 WHERE PO_NUMBER IS NOT NULL;
    Explained.
    SQL>
    SQL>
    SQL> SELECT * FROM TABLE(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 3891180274
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 77647 | 39M| 2006 (1)| 00:00:25 |
    |* 1 | TABLE ACCESS FULL| CGSBI_SHIP_DIST_S_EXTRACT | 77647 | 39M| 2006 (1)| 00:00:25 |
    Predicate Information (identified by operation id):
    1 - filter("PO_NUMBER" IS NOT NULL)
    13 rows selected.
    SQL>
    SQL>
    Kindly suggest on this...
    Thanks & Regards
    -Naveen Gangil
    Oracle DBA

    Rafi is correct. Since po_number is the filter column, the only chance you have for using an index to access the table is on that column. However, if there are few (or none) rows with null po_number, you will always have FTS. Does the table have a PK ( which probably consists of at least po_number, line_number )? If that is the case po_number could never be null and in which case you are dumping the whole table and no indexing scheme is going to improve the queri's performance. You might, repeat might, see performance improvement if you cleanse the data in the table ( to eliminate the need for UPPER(LTRIM)RTRIM())) ) before querying it so the the data does not have to be massaged before returning it.

  • 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

  • Improve Efficiency of SQL Query (reducing Hash Match cost)

    I have the following SQL query that only takes 6 seconds to run, but I am trying to get it down to around 3 seconds if possible. I've noticed that there are 3 places in the Execution Plan that have pretty high costs. 1: Hash Match (partial aggregate) - 12%.
    2: Hash Match (inner join) - 36%. 3: Index Scan - 15%.
    I've been researching Hash Match for a couple days now, but I just don't seem to be getting it. I can't seem to figure out how to decrease the cost. I've read that OUTER APPLY is really inefficient and I have two of those in my query, but I haven't been
    able to figure out a way to get the results I need without them. 
    I am fairly new to SQL so I am hoping I can get some help with this.
    SELECT wi.WorkItemID,
    wi.WorkQueueID as WorkQueueID,
    wi.WorkItemTypeID,
    wi.WorkItemIdentifier,
    wi.DisplayIdentifier,
    wi.WorkItemStatusID,
    wi.SiteID,
    wi.AdditionalIdentifier,
    wi.WorkQueueDescription,
    wi.WorkItemTypeDescription,
    wi.WorkQueueCategoryDescription,
    wi.Active,
    wi.CheckedOutOn,
    wi.CheckedOutBy_UserID,
    wi.CheckedOutBy_UserName,
    wi.CheckedOutBy_FirstName,
    wi.CheckedOutBy_LastName,
    wi.CheckedOutBy_FullName,
    wi.CheckedOutBy_Alias,
    b.[Description] as BatchDescription,
    bt.[Description] as BatchType,
    bs.[Description] as PaymentBatchStatus,
    b.PostingDate AS PostingDate,
    b.DepositDate,
    b.BatchDate,
    b.Amount as BatchTotal,
    PostedAmount = ISNULL(PostedPayments.PostedAmount, 0),
    TotalPayments = ISNULL(PostedPayments.PostedAmount, 0), --Supporting legacy views
    TotalVariance = b.Amount - ISNULL(PostedPayments.PostedAmount, 0), -- ISNULL(Payments.TotalPayments, 0),
    PaymentsCount = ISNULL(Payments.PaymentsCount, 0),
    ISNULL(b.ReferenceNumber, '') AS PaymentBatchReferenceNumber,
    b.CreatedOn,
    b.CreatedBy_UserID,
    cbu.FirstName AS CreatedBy_FirstName,
    cbu.LastName AS CreatedBy_LastName,
    cbu.DisplayName AS CreatedBy_DisplayName,
    cbu.Alias AS CreatedBy_Alias,
    cbu.UserName AS CreatedBy_UserName,
    b.LastModifiedOn,
    b.LastModifiedBy_UserID,
    lmbu.FirstName AS LastModifiedBy_FirstName,
    lmbu.LastName AS LastModifiedBy_LastName,
    lmbu.DisplayName AS LastModifiedBy_DisplayName,
    lmbu.Alias AS LastModifiedBy_Alias,
    lmbu.UserName AS LastModifiedBy_UserName,
    0 AS VisitID, --Payment work items are not associated with VisitID, but it is a PK field on all the Work Queue view models...for now...
    0 AS RCMPatientID, --Payment work items are not associated with RCMPatientID, but it is a PK field on all the Work Queue view models...for now...
    0 AS PatientID
    FROM Account.PaymentBatch AS b (NOLOCK)
    INNER JOIN ViewManager.WorkItems AS wi (NOLOCK)
    ON wi.WorkitemIdentifier = b.PaymentBatchID
    AND wi.WorkItemTypeID = 3
    INNER JOIN Account.PaymentBatchStatus AS bs (NOLOCK)
    ON b.PaymentBatchStatusID = bs.PaymentBatchStatusID
    LEFT JOIN Account.PaymentBatchType bt (NOLOCK)
    ON b.PaymentBatchTypeID = bt.PaymentBatchTypeID
    INNER JOIN ViewManager.[User] AS cbu (NOLOCK)
    ON b.CreatedBy_UserID = cbu.UserID
    INNER JOIN ViewManager.[User] AS lmbu (NOLOCK)
    ON b.LastModifiedBy_UserID = lmbu.UserID
    LEFT JOIN (
    SELECT p.PaymentBatchID
    , SUM(p.Amount) AS TotalPayments
    , COUNT(0) AS PaymentsCount
    FROM Account.Payment AS p (NOLOCK)
    WHERE p.PaymentTypeID = 1
    AND ISNULL(p.Voided, 0) = 0
    GROUP BY p.PaymentBatchID
    ) AS Payments ON b.PaymentBatchID = Payments.PaymentBatchID
    LEFT JOIN (
    SELECT p.PaymentBatchID
    , SUM(pa.Amount) AS PostedAmount
    FROM Account.Payment AS p (NOLOCK)
    INNER JOIN Account.PaymentAllocation AS PA (NOLOCK)
    ON p.PaymentID = pa.PaymentID
    AND (pa.AllocationTypeID = 101 OR pa.AllocationTypeID = 111)
    WHERE p.PaymentTypeID = 1
    AND ISNULL(p.Voided, 0) = 0
    GROUP BY p.PaymentBatchID
    ) AS PostedPayments ON b.PaymentBatchID = PostedPayments.PaymentBatchID
    OUTER APPLY (
    SELECT
    P.PaymentBatchID,
    SUM(CASE WHEN P.PaymentTypeID = 1 THEN 1 ELSE 0 END) as PaymentsCount --only count regular payments not adjustments
    FROM
    Account.Payment p (NOLOCK)
    WHERE
    p.PaymentBatchID = b.PaymentBatchID
    AND p.PaymentTypeID IN (1,2) AND ISNULL(p.Voided, 0)= 0
    GROUP BY
    P.PaymentBatchID
    ) payments
    OUTER APPLY (
    SELECT
    P.PaymentBatchID,
    SUM(pa.Amount) as PostedAmount
    FROM
    Account.PaymentAllocation pa (NOLOCK)
    INNER JOIN
    Account.Payment p (NOLOCK) ON pa.PaymentID = p.PaymentID
    INNER JOIN
    Account.AllocationType t (NOLOCK) ON pa.AllocationTypeID = t.AllocationTypeID
    WHERE
    p.PaymentBatchID = b.PaymentBatchID
    AND p.PaymentTypeID IN (1,2)
    AND ISNULL(p.Voided, 0)= 0
    --AND (t.Credit = 0
    --OR (t.Credit <> 0 And Offset_PaymentAllocationID IS NULL AND (SELECT COUNT(1) FROM Account.paymentAllocation pa2 (NOLOCK)
    -- WHERE pa2.PaymentID = pa.PaymentID AND pa2.AllocationTypeID IN (101, 111)
    -- AND pa2.Offset_PaymentAllocationID IS NULL) > 0))
    GROUP BY
    P.PaymentBatchID
    ) PostedPayments

    The percentages you see are only estimates and may not necessarily not reflect where the real bottleneck is. Particularly, if it is due to a misestimate somewhere.
    To be able to help you improve the performance, we need to see the CREATE TABLE and CREATE INDEX statements for the tables. We also need to see the actual query plan. (In XML format, not a screen shot.) Posting all this here is not practical, but you could
    upload it somewhere. (Dropbox, Google Drive etc.)
    Be very careful with the NOLOCK hint. Using the NOLOCK hint casually lead to transient erratic behaviour which is very difficult to understand. Using it consistenly through a query like you do, is definitely bad practice.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Improve performance SQL using better SQL functions

    Good afternoon,
    I am trying to improve the performance of a SQL query, embedded within a Pro*C environment.
    The query is the following:
    SELECT ri FROM
    TRANSLAT WHERE (:ora9_ogt_prfx LIKE (TRANSLAT.OGT_PRFX||'%')) AND
    (:ora9_in_prfx LIKE (TRANSLAT.IN_PRFX||'%')) AND
    (LENGTH(:ora9_in_prfx) = ASCII(TRANSLAT.IN_LGTH))
    ORDER BY LENGTH(TRANSLAT.OGT_PRFX) DESC,
    LENGTH(TRANSLAT.IN_PRFX) DESC
    The table format is the following:
    SQL> desc translat;
    Name Type
    IN_LGTH CHAR(1)
    IN_PRFX VARCHAR2(24)
    NAME VARCHAR2(20)
    OGT_PRFX VARCHAR2(24)
    OUT_PRFX VARCHAR2(24)
    RI NUMBER(18)
    SNPUPDT NUMBER
    The idea of the query is the following:
    Give the information about a tupple with following conditions:
    - The field "OGT_PREFIX" starts with ora9_ogt_prfx
    - The field "IN_PREFIX" starts with ora9_in_prfx
    - Some length variable should be ok
    and order them, first following the OGT_PRFX field, and second following the IN_PRFX field.
    Following a tkprof analysis, this query is parsed again everytime it is needed,
    despite the usage of bind variables (all variables start with a ':' character).
    Questions:
    - Why is the query parsed again every time?
    - Personally I think this is due to the '||' operator. Is there another way of saying that a variable should start with the value of a field in such a way that the '||' operator is not needed (does there exist a logical operator like "Begins_with" so that the conditions becomes "TRANSLAT.IN_PRFX Begins_with :ora9_in_prfx")?
    - Within the query, there is always a reference towards the table itself while referencing a field. Would it make any performance difference if "TRANSLAT.OGT_PRFX" is replaced by "OGT_PRFX", "TRANSLAT.IN_PRFX" by "IN_PRFX", ...?
    Thanks a lot
    Dominique
    P.s. if this thread is entered in the wrong discussion forum, please let me know.

    - Why is the query parsed again every time?Because somewhere in the code the cursor gets closed, so on a subsequent usage you have to open it again and parse again.
    - Personally I think this is due to the '||'
    operator. Is there another way of saying that a
    variable should start with the value of a field in
    such a way that the '||' operator is not needed (does
    there exist a logical operator like "Begins_with" so
    that the conditions becomes "TRANSLAT.IN_PRFX
    Begins_with :ora9_in_prfx")?I think that you don't know a reason for the seen behaviour and you are guessing here.
    Please post the tkprof output here so we can examine what is the root cause for your performance problem. And by the way, what is the response time and what is acceptable?
    - Within the query, there is always a reference
    towards the table itself while referencing a field.
    Would it make any performance difference if
    "TRANSLAT.OGT_PRFX" is replaced by "OGT_PRFX",
    "TRANSLAT.IN_PRFX" by "IN_PRFX", ...?No, in fact the use of aliases or even table names is considered a good practice, especially when more tables are involved, and in this case of only one table it doesn't really matter.
    Regards,
    Rob.

  • 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

Maybe you are looking for

  • I have problem with lcations in SRM

    Hi, Can anyone tell me how to resolve this issue. I have got 2 user ids in two different company codes and those ids are in two different back end systems. So now i want to access the company code "A " and company code " B " and their locations . wha

  • URL for 9.0.3

    Hello, I have deployed a jsp file to I:\ora9ias\j2ee\home\default-web-app\test I however have no idea what the url is to which this? I have tried http://145.254.22.145:7778/test/filename.jsp and I get a Can not find Server error. The server is starte

  • Secured folders

    I want to make a folder that cannot be accessed only by typing in a password. How can I do that?

  • Romanian characters in Description and captions

    How do I get Romanian characters into the descriptions of my photos in iPhoto so they will appear in the captions of my slideshow? I need characters like the t with the squiggly underneath and the s with the squiggly, a with a hat, a with a u above i

  • Preview Bug?

    While setting up desktop / dock items today, I decided to put Preview in a stack on the dock. I then later tried opening various documents with Preview but found the application to be unresponsive regardless of the type of doc I attempted to open. Pr