Help to optimize a query

Dear all,
we are working with Oracle 9.2.0.4 64 bits server.
Whe have a quera in a view that the response time is between 1.7 to 4 second. Some table have more than 1 million of record and other 100,000 record.
the Query is :
select * from (
  SELECT
    /*+ FIRST_ROWS(10) + INDEX_ASC(C) + INDEX_ASC(S) + INDEX_ASC(Q)*/
    L.LOT_CODE                  ,
    S.SITE_CODE                 ,
    L.FACILITY_CODE             ,
    L.PROD_CODE                 ,
    L.CREATION_DATE AS DATE_CRE ,
    NVL(SUM(C.HU_AVAILABLE_QTY),0) - ( NVL(SMP.QTE_REQ,0) + NVL(SB.QTY,0) + NVL
    (SMP2.QTE_REQ,0) )                                           AS QTE_DISPO ,
    NVL(SUM(C.HU_AVAILABLE_QTY),0)                               AS QTE_STOCK ,
    ( NVL(SMP.QTE_REQ,0) + NVL(SB.QTY,0) + NVL(SMP2.QTE_REQ,0) ) AS QTE_RESERVE,
    MIN( C.HU_EXPIRY_DATE )                 AS DATE_EXP   ,
    MIN( C.HU_EXPIRY_DATE ) - TRUNC(DBDATE) AS REM_EXPIRY ,
    COUNT(*) AS NB_HU      ,
    HU_STOR_TYPE,
    HU_BIN,
    C.SAP_BATCH_CARACT_STATUS,
    Q.STAT_QUAL_CODE,
    Q.NEED_CONFIRM
  FROM LOT L
  INNER JOIN CONTAINER C ON  (
      L.LOT_CODE        = C.LOT_CODE
    AND L.FACILITY_CODE = C.FACILITY_CODE
  INNER JOIN SITE S
  ON
      L.FACILITY_CODE = S.FACILITY_CODE
  LEFT OUTER JOIN STOCK K
  ON
      L.LOT_CODE = K.NUMLOT
  LEFT OUTER JOIN CONTAINER_STATUS CS1
  ON
      S.SITE_CODE                 = CS1.SITE_CODE
    AND C.SAP_STOCK_STATUS        = CS1.STOCK_STATUS
    AND C.SAP_BATCH_STATUS        = CS1.BATCH_STATUS
    AND C.SAP_BATCH_CARACT_STATUS = CS1.BATCH_CHARACTERISTICS
  LEFT OUTER JOIN CONTAINER_STATUS CS2
  ON
      S.SITE_CODE                  = CS2.SITE_CODE
    AND C.SAP_STOCK_STATUS         = CS2.STOCK_STATUS
    AND C.SAP_BATCH_STATUS         = CS2.BATCH_STATUS
    AND CS2.BATCH_CHARACTERISTICS IS NULL
  INNER JOIN STAT_QUALITE Q
  ON
      COALESCE(CS1.ACCEPTABLE,CS2.ACCEPTABLE,'W') = Q.STAT_QUAL_CODE
  LEFT OUTER JOIN STOCK_BOTTLES KB
  ON
      C.CONTAINER_CODE = KB.HU_NUMBER
    AND 'N'            = DELETED
    -- STOCK DECISION WAITING TO BE BOTTLED
  LEFT OUTER JOIN
      SELECT STOCK_NUMLOT,
        STOCK_STOR_TYPE  ,
        STOCK_BIN        ,
        SUM(QTE_REQ) AS QTE_REQ
      FROM SAMPLE
      WHERE DECISION_CODE = 'S'
      AND STATUT_CODE    IN ('PR','CT')
      GROUP BY STOCK_NUMLOT,
        STOCK_STOR_TYPE    ,
        STOCK_BIN
    SMP
  ON
      C.LOT_CODE       = SMP.STOCK_NUMLOT
    AND C.HU_STOR_TYPE = SMP.STOCK_STOR_TYPE
    AND C.HU_BIN       = SMP.STOCK_BIN
    -- STOCK DECISION BEING BOTTLED WITH A SOURCE HU
  LEFT OUTER JOIN
      SELECT HU_SRC_NUMBER,
        SUM(QTY) AS QTY
      FROM STOCK_BOTTLES
      WHERE HU_SRC_NUMBER IS NOT NULL
      AND BOTTLED          = 'N'
      GROUP BY HU_SRC_NUMBER
    SB
  ON
      C.CONTAINER_CODE = SB.HU_SRC_NUMBER
    -- STOCK DECISION BEING BOTTLED WITHOUT SOURCE HU
  LEFT OUTER JOIN
      SELECT STOCK_NUMLOT,
        STOCK_STOR_TYPE  ,
        STOCK_BIN        ,
        SUM(QTY) AS QTE_REQ
      FROM SAMPLE S1
      INNER JOIN STOCK_BOTTLES B1
      ON
          S1.NUMSMP = B1.NUMSMP
      WHERE DECISION_CODE  = 'S'
      AND STATUT_CODE      = 'TB'
      AND B1.HU_SRC_NUMBER = '                    '
      GROUP BY STOCK_NUMLOT,
        STOCK_STOR_TYPE    ,
        STOCK_BIN
    SMP2 ON
      C.LOT_CODE       = SMP2.STOCK_NUMLOT
    AND C.HU_STOR_TYPE = SMP2.STOCK_STOR_TYPE
    AND C.HU_BIN       = SMP2.STOCK_BIN
  WHERE K.QTE_STOCK                               IS NULL
  AND S.SITE_CODE                                  = NVL(K.SITE_CODE,S.SITE_CODE)
  AND COALESCE(CS1.ACCEPTABLE,CS2.ACCEPTABLE,'W') <> 'N'
  AND
      KB.HU_NUMBER IS NULL
    OR KB.TYPE      = 'STOCK'
  GROUP BY L.LOT_CODE        ,
    S.SITE_CODE              ,
    L.FACILITY_CODE          ,
    L.PROD_CODE              ,
    L.CREATION_DATE          ,
    HU_STOR_TYPE             ,
    HU_BIN                   ,
    C.SAP_BATCH_CARACT_STATUS,
    Q.STAT_QUAL_CODE         ,
    Q.NEED_CONFIRM           ,
    NVL(SMP.QTE_REQ,0) + NVL(SB.QTY,0) + NVL(SMP2.QTE_REQ,0)
  HAVING NVL(SUM(C.HU_AVAILABLE_QTY),0) > ( NVL(SMP.QTE_REQ,0) + NVL(SB.QTY,0)
                                                               + NVL(
    SMP2.QTE_REQ,0) )
) where PROD_CODE = '4114923'
  and  FACILITY_CODE = 'DU01'
  and  nvl( SITE_CODE , 'D9' ) = 'D9'
  and  QTE_DISPO > 0;I have put on my example a select * from (query of the view) where...
the execution time is 1.462 second. I have identify what make the query slow.
When I reproduce the query step-by-step and test every times the execution time, the execution time is 2x when I have this line :
  LEFT OUTER JOIN (SELECT STOCK_NUMLOT,STOCK_STOR_TYPE, STOCK_BIN , SUM(QTE_REQ) AS QTE_REQ FROM SAMPLE WHERE DECISION_CODE = 'S' AND STATUT_CODE IN ('PR','CT') GROUP BY STOCK_NUMLOT,STOCK_STOR_TYPE, STOCK_BIN)
           SMP ON (C.LOT_CODE = SMP.STOCK_NUMLOT AND C.HU_STOR_TYPE = SMP.STOCK_STOR_TYPE AND C.HU_BIN = SMP.STOCK_BIN)The left outer join with a subquery, is my problem. Do you now how can i change it ?
Thanks.

Hi,
There are 1 week that I analyse my query and identify that the problem is this line :
LEFT OUTER JOIN (SELECT STOCK_NUMLOT,STOCK_STOR_TYPE, STOCK_BIN , SUM(QTE_REQ) AS QTE_REQ FROM SAMPLE WHERE DECISION_CODE = 'S' AND STATUT_CODE IN ('PR','CT') GROUP BY STOCK_NUMLOT,STOCK_STOR_TYPE, STOCK_BIN)
           SMP ON (C.LOT_CODE = SMP.STOCK_NUMLOT AND C.HU_STOR_TYPE = SMP.STOCK_STOR_TYPE AND C.HU_BIN = SMP.STOCK_BIN)There is an anothers form to make this left join ?
Best regards,

Similar Messages

  • Need help on optimization of query

    Basically I had some query which should have been optimized. I did some optimization, but I guess it could be optimized more. Please help
    DATA_
    PK - ID
    FK - ID (HIER ID)
    VAL nullable
    ATTR1 not null
    ATTR2 not null
    HIER
    PK -ID
    L1 - not null
    L2 - not null
    L3 - not null
    WITH data_ AS
    SELECT 1 ID, 20 val, 1 attr1, 1 attr2
    FROM DUAL
    UNION ALL
    SELECT 2, 30, 0, 1
    FROM DUAL
    UNION ALL
    SELECT 3, 40, 1, 1
    FROM DUAL
    UNION ALL
    SELECT 4, 50, 0, 0
    FROM DUAL
    UNION ALL
    SELECT 5, 60, 1, 0
    FROM DUAL
    UNION ALL
    SELECT 6, 70, 0, 1
    FROM DUAL
    UNION ALL
    SELECT 7, 80, 1, 1
    FROM DUAL
    UNION ALL
    SELECT 8, 10, 1, 0
    FROM DUAL
    UNION ALL
    SELECT 9, 15, 1, 1
    FROM DUAL),
    hier AS
    SELECT 1 ID, 11 l1, 21 l2, 31 l3
    FROM DUAL
    UNION ALL
    SELECT 2, 11, 21, 31
    FROM DUAL
    UNION ALL
    SELECT 3, 12, 21, 31
    FROM DUAL
    UNION ALL
    SELECT 4, 13, 22, 31
    FROM DUAL
    UNION ALL
    SELECT 5, 11, 21, 31
    FROM DUAL
    UNION ALL
    SELECT 6, 12, 21, 31
    FROM DUAL
    UNION ALL
    SELECT 7, 13, 22, 31
    FROM DUAL
    UNION ALL
    SELECT 8, 14, 23, 32
    FROM DUAL
    UNION ALL
    SELECT 9, 11, 21, 31
    FROM DUAL)
    SELECT 'ALL' lev, SUM (val) avg_
    FROM data_
    UNION ALL
    SELECT 'ATTR1 = ' || attr1, SUM (val)
    FROM data_
    GROUP BY attr1
    UNION ALL
    SELECT 'ATTR2 = ' || attr2, SUM (val)
    FROM data_
    GROUP BY attr2
    UNION ALL
    SELECT 'L3 = ' || l3, SUM (val)
    FROM data_ d, hier h
    WHERE d.ID = h.ID AND l3 IN (SELECT l3
    FROM hier
    WHERE l1 = :l1)
    GROUP BY l3
    UNION ALL
    SELECT 'L2 = ' || l2, SUM (val)
    FROM data_ d, hier h
    WHERE d.ID = h.ID AND l2 IN (SELECT l2
    FROM hier
    WHERE l1 = :l1)
    GROUP BY l2
    UNION ALL
    SELECT 'L1 = ' || l1, SUM (val)
    FROM data_ d, hier h
    WHERE d.ID = h.ID AND l1 = :l1
    GROUP BY l1
    UNION ALL
    SELECT 'ID = ' || h.ID, val
    FROM data_ d, hier h
    WHERE d.ID = h.ID AND l1 = :l1
    Now it looks like
    WITH data_ AS
    SELECT 1 ID, 20 val, 1 attr1, 1 attr2
    FROM DUAL
    UNION ALL
    SELECT 2, 30, 0, 1
    FROM DUAL
    UNION ALL
    SELECT 3, 40, 1, 1
    FROM DUAL
    UNION ALL
    SELECT 4, 50, 0, 0
    FROM DUAL
    UNION ALL
    SELECT 5, 60, 1, 0
    FROM DUAL
    UNION ALL
    SELECT 6, 70, 0, 1
    FROM DUAL
    UNION ALL
    SELECT 7, 80, 1, 1
    FROM DUAL
    UNION ALL
    SELECT 8, 10, 1, 0
    FROM DUAL
    UNION ALL
    SELECT 9, 15, 1, 1
    FROM DUAL),
    hier AS
    SELECT 1 ID, 11 l1, 21 l2, 31 l3
    FROM DUAL
    UNION ALL
    SELECT 2, 11, 21, 31
    FROM DUAL
    UNION ALL
    SELECT 3, 12, 21, 31
    FROM DUAL
    UNION ALL
    SELECT 4, 13, 22, 31
    FROM DUAL
    UNION ALL
    SELECT 5, 11, 21, 31
    FROM DUAL
    UNION ALL
    SELECT 6, 12, 21, 31
    FROM DUAL
    UNION ALL
    SELECT 7, 13, 22, 31
    FROM DUAL
    UNION ALL
    SELECT 8, 14, 23, 32
    FROM DUAL
    UNION ALL
    SELECT 9, 11, 21, 31
    FROM DUAL),
    level_id AS
    (SELECT 11 l
    FROM DUAL)
    SELECT DECODE (GROUPING_ID (attr2, attr1),
    1, 'ATTR2 = ' || attr2,
    2, 'ATTR1 = ' || attr1,
    3, 'All'
    ) lev,
    SUM (val)
    FROM data_
    GROUP BY CUBE (attr2, attr1)
    HAVING GROUPING_ID (attr2, attr1) > 0
    UNION ALL
    SELECT lev, val
    FROM (SELECT DECODE (GROUPING_ID (d.ID, l1, l2, l3),
    11, 'L1 = ' || l1,
    13, 'L2 = ' || l2,
    14, 'L3 = ' || l3,
    'ID = ' || d.ID
    ) lev,
    SUM (val) val
    FROM data_ d, hier h, level_id
    WHERE d.ID = h.ID AND h.l3 IN (SELECT h1.l3
    FROM hier h1
    WHERE h1.l1 = l)
    GROUP BY CUBE (d.ID, l3, l2, l1)
    HAVING (h.l1 IS NULL OR l1 = l)
    AND GROUPING_ID (d.ID, l1, l2, l3) IN (14, 13, 11, 0)
    AND (h.l2 IS NULL OR h.l2 = (SELECT UNIQUE h1.l2
    FROM hier h1
    WHERE h1.l1 = l))
    ORDER BY GROUPING_ID (d.ID, l1, l2, l3) DESC)

    Nobody can optimize you query just from having the query. We don't know anything about your database, your data, your database configuration, table structures, indexes, or what the query is supposed to achieve etc. etc. etc.
    Take a look at this thread...
    When your query takes too long ...

  • Help with optimize analitics query .

    HI,
    I've got Oracle 10.2.0.3 query like :
    select * from
         select rank() over (partition by t1.customer_key order by
         func(t1.klt_dlugosc,t1.klt_szerokosc,t2.gemfo_dlugosc,t2.gemfo_szerokosc),rownum) as id,
         t1.customer_key,
         func(t1.klt_dlugosc,t1.klt_szerokosc,t2.gemfo_dlugosc,t2.gemfo_szerokosc) odleg_gemfo,
         t2.gemfo_id             
         from tmp_22_geo_0309 t1,
    (select * from adresy_gemfo_geo t2)) where id<3;
    PLAN_TABLE_OUTPUT
    Plan hash value: 187241240
    | Id  | Operation                | Name                           | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT         |                                |    10M|   486M|       |   109K  (2)| 00:25:28 |
    |*  1 |  VIEW                    |                                |    10M|   486M|       |   109K  (2)| 00:25:28 |
    |*  2 |   WINDOW SORT PUSHED RANK|                                |    10M|   630M|  1455M|   109K  (2)| 00:25:28 |
    |   3 |    COUNT                 |                                |       |       |       |            |          |
    |   4 |     MERGE JOIN CARTESIAN |                                |    10M|   630M|       |  9720   (3)| 00:02:17 |
    |   5 |      TABLE ACCESS FULL   | ADRESY_GEMFO_GEO               |   151 |  5738 |       |     3   (0)| 00:00:01 |
    |   6 |      BUFFER SORT         |                                | 66293 |  1812K|       |   109K  (2)| 00:25:28 |
    |   7 |       TABLE ACCESS FULL  | TMP_22_GEO_0309                       | 66293 |  1812K|       |    64   (2)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter("ID"<3)
       2 - filter(RANK() OVER ( PARTITION BY "CUSTOMER_KEY" ORDER BY
                  func("KLT_DLUGOSC","KLT_SZEROKOSC","ADRESY_GEMFO_GEO"."GEMFO_DLUGOSC","ADRESY_GEMFO_GEO"."
                  GEMFO_SZEROKOSC"),ROWNUM)<3)
    Note
       - dynamic sampling used for this statement
       is burning CPU , an d runs like 2h
    t1 is 66293 rows
    and t2 is 151 rows
    is there any way to rewrite this ?
    function func is doing some geolocation related math like sin/cos abs .
    Regards.
    Greg

    Yes, thats expected (cartesian join), tables are small .
    Function is doing geolocation calculations like:
    CREATE OR REPLACE function func (dlugosc_geo_1 number,
                                          szerokosc_geo_1 number,
                                          dlugosc_geo_2 number,
                                          szerokosc_geo_2 number) return number
    is
      a_1 number;
      c_1 number;
      d_1 number;
      metry number := 1000;
      r_ziemi number := 6371;
      pi number := 3.1415926535897932384626433832795028841972;
      dLat number;
      dLon number;
      szer_1 number;
      szer_2 number;
    begin
      dLat := abs(szerokosc_geo_2-szerokosc_geo_1)*pi/180;
      dLon := abs(dlugosc_geo_2-dlugosc_geo_1)*pi/180;
      szer_1 := szerokosc_geo_1 * pi/180;
      szer_2 := szerokosc_geo_2 * pi/180;
      a_1 := sin(dLat/2) * sin(dLat/2) +
             cos(szer_1) * cos(szer_2) *
             sin(dLon/2) * sin(dLon/2);
      c_1 := 2 * atan2(sqrt(a_1), sqrt(1-a_1));
      d_1 := round(metry * r_ziemi * c_1);
    RETURN d_1;
    end;
    /

  • Please help me optimize this query

    Hi,
    Can you’ll please recommend me if there is any way to optimize the SQL statement below.
    I have 3 tables:
    item_master: contains master list of items
    item_rentout: items currently out on rent
    item_missing: items having special status like missing, withdrawn and so on.
    I want to find items that are currently available.
    Which is items in table item_master –(minus) items in table item_rentout –(minus) items in table in item_missing.
    This is how my sql statement is:
    select item_master.item_id from item_master where item_master.item_id not in
    ((select item_id from item_rentout) union (select item_id from item_missing where status in (‘missing’,withdrawn’)))Regards,
    Raja

    In addition to what Pointless posted (which is very valuable information!) you could always try and write a logical equivalent SQL statement. It may generate a more favorable plan.
    I have written the following that I think may work but they are untested:
    SELECT  ITEM_MASTER.ITEM_ID     FROM ITEM_MASTER
    MINUS
    SELECT  ITEM_ID FROM ITEM_RENTOUT
    MINUS
    SELECT  ITEM_ID FROM ITEM_MISSING WHERE STATUS IN ('missing','withdrawn')
    SELECT  item_master.item_id
    FROM    ITEM_MASTER IM
    WHERE   NOT EXISTS
                    SELECT  NULL
                    FROM    ITEM_RENTOUT IR
                    WHERE   IR.ITEM_ID = IM.ITEM_ID
    AND     NOT EXISTS
                    SELECT  NULL
                    FROM    ITEM_MISSING IIM
                    WHERE   IIM.ITEM_ID = IM.ITEM_ID       
            )

  • Help needed to optimize the query

    Help needed to optimize the query:
    The requirement is to select the record with max eff_date from HIST_TBL and that max eff_date should be > = '01-Jan-2007'.
    This is having high cost and taking around 15mins to execute.
    Can anyone help to fine-tune this??
       SELECT c.H_SEC,
                    c.S_PAID,
                    c.H_PAID,
                    table_c.EFF_DATE
       FROM    MTCH_TBL c
                    LEFT OUTER JOIN
                       (SELECT b.SEC_ALIAS,
                               b.EFF_DATE,
                               b.INSTANCE
                          FROM HIST_TBL b
                         WHERE b.EFF_DATE =
                                  (SELECT MAX (b2.EFF_DATE)
                                     FROM HIST_TBL b2
                                    WHERE b.SEC_ALIAS = b2.SEC_ALIAS
                                          AND b.INSTANCE =
                                                 b2.INSTANCE
                                          AND b2.EFF_DATE >= '01-Jan-2007')
                               OR b.EFF_DATE IS NULL) table_c
                    ON  table_c.SEC_ALIAS=c.H_SEC
                       AND table_c.INSTANCE = 100;

    To start with, I would avoid scanning HIST_TBL twice.
    Try this
    select c.h_sec
         , c.s_paid
         , c.h_paid
         , table_c.eff_date
      from mtch_tbl c
      left
      join (
              select sec_alias
                   , eff_date
                   , instance
                from (
                        select sec_alias
                             , eff_date
                             , instance
                             , max(eff_date) over(partition by sec_alias, instance) max_eff_date
                          from hist_tbl b
                         where eff_date >= to_date('01-jan-2007', 'dd-mon-yyyy')
                            or eff_date is null
               where eff_date = max_eff_date
                  or eff_date is null
           ) table_c
        on table_c.sec_alias = c.h_sec
       and table_c.instance  = 100;

  • Need help to optimize query

    Hi
    I need help to optimize the below query.... I takes to long to execute.
    SELECT  vbak~waerk
                  vbapvbeln vbapposnr
                  vbapnetwr vbapbrgew vbap~erdat
            INTO CORRESPONDING FIELDS OF TABLE tmp_orders
            FROM vbak INNER JOIN vbap ON vbakvbeln = vbapvbeln
            WHERE vbap~matnr EQ t_mchb-matnr
            AND vbap~netwr   GT 0            
            AND vbap~brgew   GT 1                             
            AND vbak~auart     IN ('ZCAO', 'ZDDO').   
    Please help...
    Edited by: Alvaro Tejada Galindo on Mar 18, 2008 6:02 PM

    Hi,
    try this logic and see:
    data: begin of itab_for_vbak occurs 0,
          waerk type WAERK,
          vbeln type vbeln,
          end of itab_for_vbak,
          wa_for_vbak like itab_for_vbak.
    data: begin of itab_for_vbap occurs 0,
          vbeln like vbap-VBELN,
          posnr like vbap-POSNR,
          netwr like vbap-NETWR,
          brgew like vbap-brgew,
          erdat like ERDAT
          end of itab_for_vbap,
          wa_for_vbap like itab_for_vbap.
    SELECT
    waerk
    vbeln
    from
    vbak
    into table itab_for_vbak
    where
    vbak~auart IN ('ZCAO', 'ZDDO').
    select
    vbeln
    posnr
    netwr
    brgew
    erdat
    into table itab_for_vbap
    where
    vbap~matnr EQ t_mchb-matnr
    AND vbap~netwr GT 0
    AND vbap~brgew GT 1.
    loop at itab_for_vbak into wa_for_vbak.
    read table itab_for_vbap with key vbeln = wa_for_vbak-vbeln.
    if sy-subrc eq 0.
    tmp_orders-waerk = wa_for_vbak-waerk.
    tmp_orders-vbeln = wa_for_vbap-vbeln.
    tmp_orders-posnr = wa_for_vbap-posnr.
    tmp_orders-brgew = wa_for_vbap-brgew.
    tmp_orders-erdat = wa_for_vbap-erdat.
    append tmp_orders.
    endif.
    endloop.
    Please let me know how it has improved your performance or still if you have issues on this.
    Thanks,
    Vishnu.

  • Help to optimize query

    Hi pal,
    Please help me to optimize this query, this query is to slow (execute time for about 1 Million record is over 5 Hour):
    IF EXISTS(SELECT [name] FROM tempdb.sys.tables WHERE [name] like '#Temp%') BEGIN
    DROP TABLE #Temp;
    END;
    Select *,CAST(0 AS int) PreviusRowId,(CAST(Doc_Date AS VARCHAR)+CAST(Doc_Time AS VARCHAR)) AS FullTime INTO #Temp From vwStoragePricingData vw ORDER BY vw.Stock,vw.Part_No,vw.Doc_Date,vw.Doc_Time,vw.Ie_Code,vw.Doc_No
    BEGIN TRANSACTION
    SET QUOTED_IDENTIFIER ON
    SET ARITHABORT ON
    SET NUMERIC_ROUNDABORT OFF
    SET CONCAT_NULL_YIELDS_NULL ON
    SET ANSI_NULLS ON
    SET ANSI_PADDING ON
    SET ANSI_WARNINGS ON
    COMMIT
    BEGIN TRANSACTION
    GO
    ALTER TABLE #Temp ADD
    AutoAmount AS CASE WHEN RemainQty<=0 THEN 0 ELSE RemainPrice/RemainQty END
    GO
    ALTER TABLE #Temp SET (LOCK_ESCALATION = TABLE)
    GO
    COMMIT
    UPDATE #Temp
    SET PreviusRowId = (SELECT TOP 1 RowId FROM #Temp preTemp WHERE
    preTemp.Stock=#Temp.Stock AND preTemp.Part_No=#Temp.Part_No
    AND preTemp.FullTime<=#Temp.FullTime AND preTemp.Doc_No<#Temp.Doc_No ORDER BY RowId DESC)
    UPDATE #Temp
    SET RemainQty = FirstQty+InputQty-ExportQty,
    RemainPrice = FirstPrice+InputQty-ExportPrice,
    IsCalculated=1,
    IsFinished=1
    WHERE Doc_No='0'
    UPDATE
    #Temp
    SET
    #Temp.FirstPrice= Head.AutoAmount * #Temp.FirstQty ,
    #Temp.InputPrice= Head.InputQty ,
    #Temp.ExportPrice= Head.ExportQty ,
    #Temp.IsCalculated=1
    FROM
    #Temp
    INNER JOIN
    #Temp Head
    ON #Temp.RefrenceTransactId=Head.TransactId AND head.TypeIsSelfReference=1 AND #Temp.IsCalculated=0
    IF EXISTS(SELECT [name] FROM tempdb.sys.tables WHERE [name] like '#TempDate%') BEGIN
    DROP TABLE #TempDate;
    END;
    SELECT DISTINCT Doc_Date INTO #TempDate FROM #Temp
    SELECT * FROM #TempDate
    DECLARE @CurrentDate AS VARCHAR(10)
    DECLARE Date_cursor CURSOR FOR
    SELECT Doc_Date
    FROM #TempDate ORDER BY Doc_Date
    OPEN Date_cursor
    FETCH NEXT FROM Date_cursor
    INTO @CurrentDate
    WHILE @@FETCH_STATUS = 0
    BEGIN
    DECLARE @ProccessStock AS VARCHAR(3)
    DECLARE @ProccessPartNo AS VARCHAR(50)
    DECLARE Calculate_cursor CURSOR FOR
    SELECT Stock,Part_No FROM #Temp WHERE Doc_Date=@CurrentDate
    GROUP BY Doc_Date,Doc_Time,Stock,Part_No
    ORDER BY Doc_Date,Doc_Time,COUNT(RefrenceTransactId)
    OPEN Calculate_cursor
    FETCH NEXT FROM Calculate_cursor
    INTO @ProccessStock ,@ProccessPartNo
    WHILE @@FETCH_STATUS = 0
    BEGIN
    UPDATE #Temp
    SET RemainQty += (SELECT RemainQty FROM #Temp preTemp WHERE
    RowId=#Temp.PreviusRowId),
    RemainPrice += (SELECT RemainPrice FROM #Temp preTemp WHERE
    RowId=#Temp.PreviusRowId),
    IsCalculated=1,
    IsFinished=1
    WHERE Stock=@ProccessStock AND Part_No=@ProccessPartNo AND Doc_Date=@CurrentDate AND IsFinished=0
    UPDATE #Temp
    SET
    #Temp.FirstPrice= Head.AutoAmount * #Temp.FirstQty ,
    #Temp.InputPrice= Head.AutoAmount * #Temp.InputQty ,
    #Temp.ExportPrice= Head.AutoAmount * #Temp.ExportQty ,
    #Temp.IsCalculated=1
    FROM
    #Temp
    INNER JOIN
    #Temp Head
    ON #Temp.RefrenceTransactId=Head.TransactId
    WHERE
    Head.Stock=@ProccessStock AND Head.Part_No=@ProccessPartNo AND Head.Doc_Date=@CurrentDate
    -- Get the next Calculate.
    FETCH NEXT FROM Calculate_cursor
    INTO @ProccessStock ,@ProccessPartNo
    END
    CLOSE Calculate_cursor;
    DEALLOCATE Calculate_cursor;
    -- Get the next Stock.
    FETCH NEXT FROM Date_cursor
    INTO @CurrentDate
    END
    CLOSE Date_cursor;
    DEALLOCATE Date_cursor;
    SELECT * FROM #Temp
    Thank you
    Rambod Taati

    Good day Rambod
    1. We can not reproduce your situation in order to optimize the query, since we dont have vwStoragePricingData tbale for example. Therefore, we can only comment on theoretical "golden rules".
    It is highly recomend to post DDL+DML for any relevant element, and give us the tools to reproduce your situation as close as we can
    2. We can not check query plan without having the tables in our server, therefore we we can not see what really going there :-( 
    3. Olaf mentioned the most important issues... I can add some points in general, which might improve your query,
    I see several times updating the temp table. 
    >> First update, might use massive table scan!
       * An index on the temp table might do great.
          One of the most valuable assets of a temp table (#temp) is the ability to add either a clustered or nonclustered index.
          Additionally, #temp tables allow for the auto-generated statistics to be created against them.
       * Moreover, we have no information on your server version.
          If you are using SQL 2012 or newer then you might get better result using LEAD/LAG functions 
    >> second update, you should try to combine with the first one. If i notice correctly
    (again we could not check or see the anything since we dont have information to reproduce), then you can do this in a single update. Probably the third update as well (but this might need more complex query since you use the result of first
    update for this update)
    >> Same comment go on second temp table...
    >> as Olaf mentioned you should try to work with SET, and not row by row using cursor or any type of looping.
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • Need help in optimizing the query with joins and group by clause

    I am having problem in executing the query below.. it is taking lot of time. To simplify, I have added the two tables FILE_STATUS = stores the file load details and COMM table that is actual business commission table showing records successfully processed and which records were transmitted to other system. Records with status = T is trasnmitted to other system and traansactions with P is pending.
    CREATE TABLE FILE_STATUS
    (FILE_ID VARCHAR2(14),
    FILE_NAME VARCHAR2(20),
    CARR_CD VARCHAR2(5),
    TOT_REC NUMBER,
    TOT_SUCC NUMBER);
    CREATE TABLE COMM
    (SRC_FILE_ID VARCHAR2(14),
    REC_ID NUMBER,
    STATUS CHAR(1));
    INSERT INTO FILE_STATUS VALUES ('12345678', 'CM_LIBM.TXT', 'LIBM', 5, 4);
    INSERT INTO FILE_STATUS VALUES ('12345679', 'CM_HIPNT.TXT', 'HIPNT', 4, 0);
    INSERT INTO COMM VALUES ('12345678', 1, 'T');
    INSERT INTO COMM VALUES ('12345678', 3, 'T');
    INSERT INTO COMM VALUES ('12345678', 4, 'P');
    INSERT INTO COMM VALUES ('12345678', 5, 'P');
    COMMIT;Here is the query that I wrote to give me the details of the file that has been loaded into the system. It reads the file status and commission table to show file name, total records loaded, total records successfully loaded to the commission table and number of records that has been finally transmitted (status=T) to other systems.
    SELECT
        FS.CARR_CD
        ,FS.FILE_NAME
        ,FS.FILE_ID
        ,FS.TOT_REC
        ,FS.TOT_SUCC
        ,NVL(C.TOT_TRANS, 0) TOT_TRANS
    FROM FILE_STATUS FS
    LEFT JOIN
        SELECT SRC_FILE_ID, COUNT(*) TOT_TRANS
        FROM COMM
        WHERE STATUS = 'T'
        GROUP BY SRC_FILE_ID
    ) C ON C.SRC_FILE_ID = FS.FILE_ID
    WHERE FILE_ID = '12345678';In production this query has more joins and is taking lot of time to process.. the main culprit for me is the join on COMM table to get the count of number of transactions transmitted. Please can you give me tips to optimize this query to get results faster? Do I need to remove group and use partition or something else. Please help!

    I get 2 rows if I use my query with your new criteria. Did you commit the record if you are using a second connection to query? Did you remove the criteria for file_id?
    select carr_cd, file_name, file_id, tot_rec, tot_succ, tot_trans
      from (select fs.carr_cd,
                   fs.file_name,
                   fs.file_id,
                   fs.tot_rec,
                   fs.tot_succ,
                   count(case
                            when c.status = 'T' then
                             1
                            else
                             null
                          end) over(partition by c.src_file_id) tot_trans,
                   row_number() over(partition by c.src_file_id order by null) rn
              from file_status fs
              left join comm c
                on c.src_file_id = fs.file_id
             where carr_cd = 'LIBM')
    where rn = 1;
    CARR_CD FILE_NAME            FILE_ID           TOT_REC   TOT_SUCC  TOT_TRANS
    LIBM    CM_LIBM.TXT          12345678                5          4          2
    LIBM    CM_LIBM.TXT          12345677               10          0          0Using RANK can potentially produce multiple rows to be returned though your data may prevent this. ROW_NUMBER will always prevent duplicates. The ordering of the analytical function is irrelevant in your query if you use ROW_NUMBER. You can remove the outermost query and inspect the data returned by the inner query;
    select fs.carr_cd,
           fs.file_name,
           fs.file_id,
           fs.tot_rec,
           fs.tot_succ,
           count(case
                    when c.status = 'T' then
                     1
                    else
                     null
                  end) over(partition by c.src_file_id) tot_trans,
           row_number() over(partition by c.src_file_id order by null) rn
    from file_status fs
    left join comm c
    on c.src_file_id = fs.file_id
    where carr_cd = 'LIBM';
    CARR_CD FILE_NAME            FILE_ID           TOT_REC   TOT_SUCC  TOT_TRANS         RN
    LIBM    CM_LIBM.TXT          12345678                5          4          2          1
    LIBM    CM_LIBM.TXT          12345678                5          4          2          2
    LIBM    CM_LIBM.TXT          12345678                5          4          2          3
    LIBM    CM_LIBM.TXT          12345678                5          4          2          4
    LIBM    CM_LIBM.TXT          12345677               10          0          0          1

  • Help tune this monster query please

    Hi, I have a query that runs for a long time. Its a system generated query but I need to improve its performance. I have enough indexes on the tables. Here is the query, its explain plan and the tkprof:
    The QUERY
    SELECT FD.FORM_ID, FD.FIELD_NAME, FD.FIELD_TEXT, FD.OPTION_TEXT, FD.OPTION_TYPE, FD.FIELD_ORDER, FD.LIST_ORDER,
    FD.MULTIPLE_ANSWER, FD.FIELD_INSTANCE, NVL(AD.APPS,0) APPS
    FROM (
        SELECT FIELD_NAME, FIELD_VALUE, INSTANCE, COUNT(0) APPS
        FROM APPLICATION_DATA AD
        WHERE APPLICATION_ID IN (
            SELECT A.APPLICATION_ID
            FROM APPLICATIONS A
            WHERE A.DELETED = 0 AND DECODE(A.TRAY,'Incomplete','Incomplete','Complete') = 'Complete' AND A.JOB_ID IN (
                SELECT JOB_ID
                FROM JOBS J
                WHERE J.ACCOUNT_ID IN (
                    SELECT ACCOUNT_ID
                        FROM AGENCY_ACCOUNTS CONNECT BY ACCOUNT_ID = PRIOR AGENCY_ID START WITH ACCOUNT_ID = J.ACCOUNT_ID ) )                  AND A.ACCOUNT_ID IN (
                        SELECT ACCOUNT_ID
                        FROM AGENCY_ACCOUNTS CONNECT BY ACCOUNT_ID = PRIOR AGENCY_ID START WITH ACCOUNT_ID = 113346 ) AND                       FIELD_NAME IN (
                            SELECT FIELD_NAME FROM APPLICATION_FIELDS
                                WHERE FIELD_TYPE IN ('Checkbox','Radio','Select','SelectM', 'RadioHoriz','RadioPara') ) )
        GROUP BY FIELD_NAME, FIELD_VALUE, INSTANCE ) AD, (
            SELECT AF.FORM_ID, AF.FIELD_NAME, AF.FIELD_TEXT, AFO.OPTION_TEXT, AFO.OPTION_TYPE, AF.FIELD_ORDER, AFO.LIST_ORDER,
            DECODE(AF.FIELD_TYPE,'Checkbox',1,'SelectM',1,0) MULTIPLE_ANSWER, AF.FIELD_INSTANCE
            FROM APPLICATION_FIELDS AF, APPLICATION_FIELD_OPTIONS AFO, JOB_FORMS JF
            WHERE AFO.FIELD_NAME = AF.FIELD_NAME AND AFO.FORM_ID = AF.FORM_ID AND JF.FORM_ID = AF.FORM_ID AND AF.FIELD_TYPE IN
            ('Checkbox','Radio','Select','SelectM', 'RadioHoriz','RadioPara') AND JF.JOB_ID IN (
                SELECT JOB_ID
                FROM JOBS J
                WHERE J.ACCOUNT_ID IN (
                    SELECT ACCOUNT_ID
                    FROM AGENCY_ACCOUNTS CONNECT BY ACCOUNT_ID = PRIOR AGENCY_ID START WITH ACCOUNT_ID = 113346 ) ) ) FD
    WHERE AD.FIELD_NAME = FD.FIELD_NAME AND AD.FIELD_VALUE = FD.OPTION_TEXT AND AD.INSTANCE = FD.FIELD_INSTANCE
    GROUP BY FD.FORM_ID, FD.FIELD_NAME, FD.FIELD_TEXT, FD.OPTION_TEXT, FD.OPTION_TYPE, FD.FIELD_ORDER, FD.LIST_ORDER,
    FD.MULTIPLE_ANSWER, FD.FIELD_INSTANCE, NVL(AD.APPS,0)
    ORDER BY FD.FORM_ID ASC, FD.FIELD_ORDER ASCEXPLAIN PLAN OUTPUT
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    Plan hash value: 3519364953                                                                                                                                                                            
    | Id  | Operation                                   | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |                                                                             
    |   0 | SELECT STATEMENT                            |                            |     1 |   120 |   763   (2)| 00:00:10 |                                                                             
    |   1 |  SORT GROUP BY                              |                            |     1 |   120 |   763   (2)| 00:00:10 |                                                                             
    |   2 |   VIEW                                      |                            |     1 |   120 |   762   (1)| 00:00:10 |                                                                             
    |   3 |    HASH GROUP BY                            |                            |     1 |   220 |   762   (1)| 00:00:10 |                                                                             
    |*  4 |     FILTER                                  |                            |       |       |            |          |                                                                             
    |*  5 |      TABLE ACCESS BY INDEX ROWID            | APPLICATION_DATA           |     1 |    45 |     6   (0)| 00:00:01 |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    |   6 |       NESTED LOOPS                          |                            |    40 |  8800 |   486   (2)| 00:00:06 |                                                                             
    |*  7 |        HASH JOIN                            |                            |    60 | 10500 |   125   (4)| 00:00:02 |                                                                             
    |*  8 |         HASH JOIN                           |                            |    60 |  7320 |    53   (6)| 00:00:01 |                                                                             
    |   9 |          NESTED LOOPS                       |                            |    11 |   297 |     9  (12)| 00:00:01 |                                                                             
    |  10 |           VIEW                              | VW_NSO_3                   |     3 |    15 |     5   (0)| 00:00:01 |                                                                             
    |  11 |            HASH UNIQUE                      |                            |     3 |    69 |            |          |                                                                             
    |  12 |             TABLE ACCESS BY INDEX ROWID     | JOBS                       |     3 |    30 |     3   (0)| 00:00:01 |                                                                             
    |  13 |              NESTED LOOPS                   |                            |     3 |    69 |     5   (0)| 00:00:01 |                                                                             
    |  14 |               VIEW                          | VW_NSO_1                   |     1 |    13 |     2   (0)| 00:00:01 |                                                                             
    |* 15 |                CONNECT BY WITH FILTERING    |                            |       |       |            |          |                                                                             
    |  16 |                 TABLE ACCESS BY INDEX ROWID | AGENCY_ACCOUNTS            |       |       |            |          |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    |* 17 |                  INDEX UNIQUE SCAN          | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |     5 |     1   (0)| 00:00:01 |                                                                             
    |  18 |                 NESTED LOOPS                |                            |       |       |            |          |                                                                             
    |  19 |                  BUFFER SORT                |                            |       |       |            |          |                                                                             
    |  20 |                   CONNECT BY PUMP           |                            |       |       |            |          |                                                                             
    |  21 |                  TABLE ACCESS BY INDEX ROWID| AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    |* 22 |                   INDEX UNIQUE SCAN         | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |       |     1   (0)| 00:00:01 |                                                                             
    |* 23 |                 TABLE ACCESS FULL           | AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    |* 24 |               INDEX RANGE SCAN              | JOBS_ACCOUNT_ID            |     3 |       |     1   (0)| 00:00:01 |                                                                             
    |* 25 |           INDEX RANGE SCAN                  | JOBS_FORMS_JID_FID         |     4 |    88 |     1   (0)| 00:00:01 |                                                                             
    |* 26 |          TABLE ACCESS FULL                  | APPLICATION_FIELDS         |  3579 |   332K|    43   (3)| 00:00:01 |                                                                             
    |  27 |         TABLE ACCESS FULL                   | APPLICATION_FIELD_OPTIONS  | 32897 |  1702K|    72   (3)| 00:00:01 |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    |* 28 |        INDEX RANGE SCAN                     | IDX$$_B8D40001             |     4 |       |     3   (0)| 00:00:01 |                                                                             
    |* 29 |      FILTER                                 |                            |       |       |            |          |                                                                             
    |  30 |       MERGE JOIN CARTESIAN                  |                            |     3 |   225 |    11   (0)| 00:00:01 |                                                                             
    |  31 |        NESTED LOOPS                         |                            |     1 |    53 |     6   (0)| 00:00:01 |                                                                             
    |  32 |         NESTED LOOPS                        |                            |     1 |    40 |     4   (0)| 00:00:01 |                                                                             
    |* 33 |          TABLE ACCESS BY INDEX ROWID        | APPLICATIONS               |     1 |    30 |     3   (0)| 00:00:01 |                                                                             
    |* 34 |           INDEX UNIQUE SCAN                 | APPS_APP_ID                |     1 |       |     2   (0)| 00:00:01 |                                                                             
    |  35 |          TABLE ACCESS BY INDEX ROWID        | JOBS                       | 18780 |   183K|     1   (0)| 00:00:01 |                                                                             
    |* 36 |           INDEX UNIQUE SCAN                 | JOBS_JOB_ID                |     1 |       |     0   (0)| 00:00:01 |                                                                             
    |* 37 |         VIEW                                | VW_NSO_2                   |     1 |    13 |     2   (0)| 00:00:01 |                                                                             
    |* 38 |          CONNECT BY WITH FILTERING          |                            |       |       |            |          |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    |  39 |           TABLE ACCESS BY INDEX ROWID       | AGENCY_ACCOUNTS            |       |       |            |          |                                                                             
    |* 40 |            INDEX UNIQUE SCAN                | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |     5 |     1   (0)| 00:00:01 |                                                                             
    |  41 |           NESTED LOOPS                      |                            |       |       |            |          |                                                                             
    |  42 |            BUFFER SORT                      |                            |       |       |            |          |                                                                             
    |  43 |             CONNECT BY PUMP                 |                            |       |       |            |          |                                                                             
    |  44 |            TABLE ACCESS BY INDEX ROWID      | AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    |* 45 |             INDEX UNIQUE SCAN               | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |       |     1   (0)| 00:00:01 |                                                                             
    |* 46 |           TABLE ACCESS FULL                 | AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    |  47 |        BUFFER SORT                          |                            |     3 |    66 |     9   (0)| 00:00:01 |                                                                             
    |  48 |         INLIST ITERATOR                     |                            |       |       |            |          |                                                                             
    |* 49 |          INDEX RANGE SCAN                   | IDX$$_91CA0001             |     3 |    66 |     5   (0)| 00:00:01 |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    |* 50 |       FILTER                                |                            |       |       |            |          |                                                                             
    |* 51 |        CONNECT BY WITH FILTERING            |                            |       |       |            |          |                                                                             
    |  52 |         TABLE ACCESS BY INDEX ROWID         | AGENCY_ACCOUNTS            |       |       |            |          |                                                                             
    |* 53 |          INDEX UNIQUE SCAN                  | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |     5 |     1   (0)| 00:00:01 |                                                                             
    |  54 |         NESTED LOOPS                        |                            |       |       |            |          |                                                                             
    |  55 |          BUFFER SORT                        |                            |       |       |            |          |                                                                             
    |  56 |           CONNECT BY PUMP                   |                            |       |       |            |          |                                                                             
    |  57 |          TABLE ACCESS BY INDEX ROWID        | AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    |* 58 |           INDEX UNIQUE SCAN                 | AGENCY_ACCOUNTS_ACCOUNT_ID |     1 |       |     1   (0)| 00:00:01 |                                                                             
    |* 59 |         TABLE ACCESS FULL                   | AGENCY_ACCOUNTS            |     1 |    10 |     2   (0)| 00:00:01 |                                                                             
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
    Predicate Information (identified by operation id):                                                                                                                                                    
       4 - filter( EXISTS (SELECT 0 FROM "APPLICATIONS" "A","JOBS" "SYS_ALIAS_1", (SELECT "ACCOUNT_ID" "$nso_col_1"                                                                                        
                  FROM "AGENCY_ACCOUNTS" "AGENCY_ACCOUNTS" WHERE "ACCOUNT_ID"=NULL) "VW_NSO_2","APPLICATION_FIELDS"                                                                                        
                  "APPLICATION_FIELDS" WHERE  EXISTS (SELECT 0 FROM "AGENCY_ACCOUNTS" "AGENCY_ACCOUNTS" WHERE "ACCOUNT_ID"=NULL AND                                                                        
                  ("ACCOUNT_ID"=:B1)) AND ("FIELD_TYPE"='Checkbox' OR "FIELD_TYPE"='Radio' OR "FIELD_TYPE"='RadioHoriz' OR                                                                                 
                  "FIELD_TYPE"='RadioPara' OR "FIELD_TYPE"='Select' OR "FIELD_TYPE"='SelectM') AND "FIELD_NAME"=:B2 AND                                                                                    
                  "A"."ACCOUNT_ID"="$nso_col_1" AND "A"."JOB_ID"="JOB_ID" AND "A"."APPLICATION_ID"=:B3 AND                                                                                                 
                  DECODE("A"."TRAY",'Incomplete','Incomplete','Complete')='Complete' AND "A"."DELETED"=0))                                                                                                 
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
       5 - filter("FIELD_NAME"="AF"."FIELD_NAME" AND "INSTANCE"="AF"."FIELD_INSTANCE")                                                                                                                     
       7 - access("AFO"."FIELD_NAME"="AF"."FIELD_NAME" AND "AFO"."FORM_ID"="AF"."FORM_ID")                                                                                                                 
       8 - access("JF"."FORM_ID"="AF"."FORM_ID")                                                                                                                                                           
      15 - filter("ACCOUNT_ID"=113346)                                                                                                                                                                     
      17 - access("ACCOUNT_ID"=113346)                                                                                                                                                                     
      22 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
      23 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
      24 - access("J"."ACCOUNT_ID"="$nso_col_1")                                                                                                                                                           
      25 - access("JF"."JOB_ID"="$nso_col_1")                                                                                                                                                              
      26 - filter("AF"."FIELD_TYPE"='Checkbox' OR "AF"."FIELD_TYPE"='Radio' OR "AF"."FIELD_TYPE"='RadioHoriz' OR                                                                                           
                  "AF"."FIELD_TYPE"='RadioPara' OR "AF"."FIELD_TYPE"='Select' OR "AF"."FIELD_TYPE"='SelectM')                                                                                              
    PLAN_TABLE_OUTPUT  FOR THE QUERY                                                                                                                                                                                    
      28 - access("FIELD_VALUE"="AFO"."OPTION_TEXT")                                                                                                                                                       
      29 - filter( EXISTS (SELECT 0 FROM "AGENCY_ACCOUNTS" "AGENCY_ACCOUNTS" WHERE "ACCOUNT_ID"=NULL AND                                                                                                   
                  ("ACCOUNT_ID"=:B1)))                                                                                                                                                                     
      33 - filter(DECODE("A"."TRAY",'Incomplete','Incomplete','Complete')='Complete' AND "A"."DELETED"=0)                                                                                                  
      34 - access("A"."APPLICATION_ID"=:B1)                                                                                                                                                                
      36 - access("A"."JOB_ID"="JOB_ID")                                                                                                                                                                   
      37 - filter("A"."ACCOUNT_ID"="$nso_col_1")                                                                                                                                                           
      38 - filter("ACCOUNT_ID"=113346)                                                                                                                                                                     
      40 - access("ACCOUNT_ID"=113346)                                                                                                                                                                     
      45 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
      46 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
    PLAN_TABLE_OUTPUT                                                                                                                                                                                      
      49 - access("FIELD_NAME"=:B1 AND ("FIELD_TYPE"='Checkbox' OR "FIELD_TYPE"='Radio' OR "FIELD_TYPE"='RadioHoriz'                                                                                       
                  OR "FIELD_TYPE"='RadioPara' OR "FIELD_TYPE"='Select' OR "FIELD_TYPE"='SelectM'))                                                                                                         
      50 - filter("ACCOUNT_ID"=:B1)                                                                                                                                                                        
      51 - filter("ACCOUNT_ID"=:B1)                                                                                                                                                                        
      53 - access("ACCOUNT_ID"=:B1)                                                                                                                                                                        
      58 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
      59 - access("ACCOUNT_ID"=NULL)                                                                                                                                                                       
    106 rows selected.TKPROF FOR THE QUERY
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.05       0.08          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch       17   1040.45    1018.36          0   48926569          0         229
    total       19   1040.50    1018.44          0   48926569          0         229
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 68
    Rows     Row Source Operation
        229  SORT GROUP BY (cr=48926569 pr=0 pw=0 time=1018362160 us)
        454   VIEW  (cr=48926569 pr=0 pw=0 time=1018361382 us)
        454    HASH GROUP BY (cr=48926569 pr=0 pw=0 time=1018360468 us)
    185302     FILTER  (cr=48926569 pr=0 pw=0 time=877249113 us)
    1440799      TABLE ACCESS BY INDEX ROWID APPLICATION_DATA (cr=11309333 pr=0 pw=0 time=213262026 us)
    82907114       NESTED LOOPS  (cr=174051 pr=0 pw=0 time=166906535 us)
       1790        HASH JOIN  (cr=625 pr=0 pw=0 time=41617 us)
        121         HASH JOIN  (cr=310 pr=0 pw=0 time=11263 us)
         39          NESTED LOOPS  (cr=121 pr=0 pw=0 time=6894 us)
         44           VIEW  VW_NSO_3 (cr=75 pr=0 pw=0 time=6424 us)
         44            HASH UNIQUE (cr=75 pr=0 pw=0 time=6333 us)
         44             TABLE ACCESS BY INDEX ROWID JOBS (cr=75 pr=0 pw=0 time=3090 us)
         52              NESTED LOOPS  (cr=32 pr=0 pw=0 time=58177 us)
          7               VIEW  VW_NSO_1 (cr=23 pr=0 pw=0 time=1242 us)
          7                CONNECT BY WITH FILTERING (cr=23 pr=0 pw=0 time=1212 us)
          1                 TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=3 pr=0 pw=0 time=185 us)
          1                  INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=2 pr=0 pw=0 time=100 us)(object id 60086)
          6                 NESTED LOOPS  (cr=20 pr=0 pw=0 time=590 us)
          7                  BUFFER SORT (cr=0 pr=0 pw=0 time=248 us)
          7                   CONNECT BY PUMP  (cr=0 pr=0 pw=0 time=95 us)
          6                  TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=20 pr=0 pw=0 time=314 us)
          6                   INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=14 pr=0 pw=0 time=188 us)(object id 60086)
          0                 TABLE ACCESS FULL AGENCY_ACCOUNTS (cr=0 pr=0 pw=0 time=0 us)
         44               INDEX RANGE SCAN JOBS_ACCOUNT_ID (cr=9 pr=0 pw=0 time=280 us)(object id 60253)
         39           INDEX RANGE SCAN JOBS_FORMS_JID_FID (cr=46 pr=0 pw=0 time=968 us)(object id 60299)
       3579          TABLE ACCESS FULL APPLICATION_FIELDS (cr=189 pr=0 pw=0 time=14469 us)
      32524         TABLE ACCESS FULL APPLICATION_FIELD_OPTIONS (cr=315 pr=0 pw=0 time=32629 us)
    82905323        INDEX RANGE SCAN IDX$$_B8D40001 (cr=173426 pr=0 pw=0 time=83870105 us)(object id 60121)
    185297      FILTER  (cr=37617236 pr=0 pw=0 time=749052070 us)
    185297       MERGE JOIN CARTESIAN (cr=37617196 pr=0 pw=0 time=742583363 us)
    185297        NESTED LOOPS  (cr=35393366 pr=0 pw=0 time=706772617 us)
    1139675         NESTED LOOPS  (cr=9180841 pr=0 pw=0 time=84949686 us)
    1140164          TABLE ACCESS BY INDEX ROWID APPLICATIONS (cr=5760834 pr=0 pw=0 time=46774108 us)
    1440060           INDEX UNIQUE SCAN APPS_APP_ID (cr=4320774 pr=0 pw=0 time=24380604 us)(object id 60107)
    1139675          TABLE ACCESS BY INDEX ROWID JOBS (cr=3420007 pr=0 pw=0 time=28126171 us)
    1139675           INDEX UNIQUE SCAN JOBS_JOB_ID (cr=2280328 pr=0 pw=0 time=14563524 us)(object id 60252)
    185297         VIEW  VW_NSO_2 (cr=26212525 pr=0 pw=0 time=613602445 us)
    6866175          CONNECT BY WITH FILTERING (cr=26212525 pr=0 pw=0 time=614183170 us)
    1139675           TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=3419025 pr=0 pw=0 time=24323520 us)
    1139675            INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=2279350 pr=0 pw=0 time=13905212 us)(object id 60086)
    6838050           NESTED LOOPS  (cr=22793500 pr=0 pw=0 time=388173853 us)
    7977725            BUFFER SORT (cr=0 pr=0 pw=0 time=178812411 us)
    7977725             CONNECT BY PUMP  (cr=0 pr=0 pw=0 time=57522094 us)
    6838050            TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=22793500 pr=0 pw=0 time=179425469 us)
    6838050             INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=15955450 pr=0 pw=0 time=113988543 us)(object id 60086)
          0           TABLE ACCESS FULL AGENCY_ACCOUNTS (cr=0 pr=0 pw=0 time=0 us)
    185297        BUFFER SORT (cr=2223830 pr=0 pw=0 time=24721936 us)
    1208625         INLIST ITERATOR  (cr=2223830 pr=0 pw=0 time=26470412 us)
    1208625          INDEX RANGE SCAN IDX$$_91CA0001 (cr=2223830 pr=0 pw=0 time=18174073 us)(object id 60129)
          2       FILTER  (cr=40 pr=0 pw=0 time=1292 us)
          2        CONNECT BY WITH FILTERING (cr=40 pr=0 pw=0 time=1276 us)
          2         TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=6 pr=0 pw=0 time=86 us)
          2          INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=4 pr=0 pw=0 time=46 us)(object id 60086)
         10         NESTED LOOPS  (cr=34 pr=0 pw=0 time=791 us)
         12          BUFFER SORT (cr=0 pr=0 pw=0 time=369 us)
         12           CONNECT BY PUMP  (cr=0 pr=0 pw=0 time=127 us)
         10          TABLE ACCESS BY INDEX ROWID AGENCY_ACCOUNTS (cr=34 pr=0 pw=0 time=376 us)
         10           INDEX UNIQUE SCAN AGENCY_ACCOUNTS_ACCOUNT_ID (cr=24 pr=0 pw=0 time=242 us)(object id 60086)
          0         TABLE ACCESS FULL AGENCY_ACCOUNTS (cr=0 pr=0 pw=0 time=0 us)Any help in tuning this query to run faster will be highly appreciated. I also noticed merge join certesian on the tkprof and explain plan. Any idea in takling that will also be appreciated.
    Cheers,
    Ade

    It's quite hard to tune a query without seeing the table structure and available indices as well as relationship between each other but I'll try.
    In your sql which you've given the table alias AD, you have this filter criteria
                  AND    FIELD_NAME IN (                        
                         SELECT FIELD_NAME
                         FROM   APPLICATION_FIELDS                            
                         WHERE  FIELD_TYPE IN ('Checkbox','Radio','Select','SelectM', 'RadioHoriz','RadioPara')
                         ) </br>
    My question is, is FIELD_NAME a column in the APPLICATION_DATA table? If it is, try moving this clause outside of the current sub-query it is in, i.e. one more level up. It looks like you put them inside the wrong level.
    I would also try converting this <COL> IN <SUB-QUERY> to a join, if that wouldn't affect the no. of rows returned. I can't tell for sure since I dont know the relationship between your tables.
    It looks to me like you're doing this
    SELECT <col list>
    FROM   ( SELECT                                         -- LEVEL 1
             FROM   APPLICATION_DATA AD
             WHERE  AD.APPLICAITON_ID IN (                  -- LEVEL 2
                    SELECT
                    FROM   APPLICATIONS A
                    WHERE  A.JOB_ID IN (
                           <SUBQUERY>
                    AND    A.ACCOUNT_ID IN (
                           <SUBQUERY>
                    AND FIELDNAME IN ( -- SHOULD BE INSIDE LEVEL1
    <SUBQUERY>
           ) AD,
           ( SELECT ....
           ) FD
    WHERE  ....

  • Help for optimization of procedure

    Hi,
    I am having following procedure it is accessing LY_RWPT_SUCCESS table having 2501818 records. i want to insert data into LY_RWPT_cap_SUCCESS with following logic but its taking lot of time .
    How we can optimize this query to give better result. pls help.
    CREATE OR REPLACE PROCEDURE "LY_PRODUCT_CAPPING_old"(P_MONTH VARCHAR2) IS
    --v_sum_rewards number
    V_SUM_REWARDS integer;
    V_FLAG VARCHAR2(1);
    V_AMOUNT integer;
    V_REWARD NUMBER;
    V_REMARKS VARCHAR2(1000);
    cursor c1 is
    select *
    from LY_RWPT_SUCCESS
    where as_of_month = P_MONTH
    -- and source_account_number ='000101006399'
    order by source_account_number asc,
    product_code asc,
    transaction_id asc,
    transaction_date asc;
    begin
    DELETE FROM LY_RWPT_CAP_SUCCESS WHERE AS_OF_MONTH = P_MONTH;
    for i in c1 loop
    V_REWARD := I.REWARDS;
    /*select nvl(sum(rewards),0) INTO V_SUM_REWARDS from ly_rwpt_cap_success_temp
    where as_of_month = P_MONTH
    and product_code = I.PRODUCT_CODE
    AND SOURCE_ACCOUNT_NUMBER = I.SOURCE_ACCOUNT_NUMBER
    and partial_flag in( 'F','P');*/
    if V_REWARD != 0 THEN
    select nvl(sum(rewards), 0)
    INTO V_SUM_REWARDS
    from ly_rwpt_cap_success
    where as_of_month = P_MONTH
    and product_code = I.PRODUCT_CODE
    AND SOURCE_ACCOUNT_NUMBER = I.SOURCE_ACCOUNT_NUMBER
    and partial_flag in ('F', 'P');
    IF (V_SUM_REWARDS >= I.PRODUCT_CAPPING) THEN
    V_REMARKS := i.remarks || ' but receiving ' || ' ' || 0 ||
    ' points as reached to product capping';
    -- V_REMARKS := i.PRODUCT_NAME ||'transaction successfully earned'||' ' ||0 ;
    V_FLAG := 'N';
    INSERT INTO LY_RWPT_CAP_SUCCESS
    VALUES
    (I.source_account_number,
    I.cust_id,
    I.customer_status_code,
    I.product_code,
    I.value,
    I.transaction_date,
    I.processing_date,
    I.balance,
    I.eligible_tag,
    0,
    I.transaction_id,
    I.payee_name,
    V_REMARKS,
    V_FLAG,
    I.as_of_month,
    I.product_name,
    I.product_capping,
    I.CUSTOMER_SEGMENT,
    I.RD_ACCOUNT_NBR,
    I.MEMBER_CUST_ID);
    COMMIT;
    ELSIF (V_SUM_REWARDS = 0 AND V_REWARD <= I.PRODUCT_CAPPING) THEN
    V_REMARKS := I.REMARKS;
    --V_REMARKS := i.PRODUCT_NAME ||'transaction successfully earned'||' ' || V_REWARD ;
    V_FLAG := 'F';
    INSERT INTO LY_RWPT_CAP_SUCCESS
    VALUES
    (I.source_account_number,
    I.cust_id,
    I.customer_status_code,
    I.product_code,
    I.value,
    I.transaction_date,
    I.processing_date,
    I.balance,
    I.eligible_tag,
    V_REWARD,
    I.transaction_id,
    I.payee_name,
    V_REMARKS,
    V_FLAG,
    I.as_of_month,
    I.product_name,
    I.product_capping,
    I.CUSTOMER_SEGMENT,
    I.RD_ACCOUNT_NBR,
    I.MEMBER_CUST_ID
    COMMIT;
    ELSIF (i.product_capping < (V_SUM_REWARDS + V_REWARD)) then
    V_AMOUNT := ABS(I.PRODUCT_CAPPING - V_SUM_REWARDS);
    V_REMARKS := i.remarks || ' but earned ' || ' ' || V_AMOUNT ||
    ' partial points' || ' as exceeding product capping';
    -- V_REMARKS := i.PRODUCT_NAME ||'transaction successfully earned'||' ' || V_AMOUNT ;
    V_FLAG := 'P';
    INSERT INTO LY_RWPT_CAP_SUCCESS
    VALUES
    (I.source_account_number,
    I.cust_id,
    I.customer_status_code,
    I.product_code,
    I.value,
    I.transaction_date,
    I.processing_date,
    I.balance,
    I.eligible_tag,
    V_AMOUNT,
    I.transaction_id,
    I.payee_name,
    V_REMARKS,
    V_FLAG,
    I.as_of_month,
    I.product_name,
    I.product_capping,
    I.CUSTOMER_SEGMENT,
    I.RD_ACCOUNT_NBR,
    I.MEMBER_CUST_ID);
    COMMIT;
    ELSIF
    (i.product_capping >= (V_SUM_REWARDS + V_REWARD)) then
    V_REMARKS := I.REMARKS;
    -- V_REMARKS := i.PRODUCT_NAME ||'transaction successfully earned'||' ' || V_REWARD ;
    V_FLAG := 'F';
    INSERT INTO LY_RWPT_CAP_SUCCESS
    VALUES
    (I.source_account_number,
    I.cust_id,
    I.customer_status_code,
    I.product_code,
    I.value,
    I.transaction_date,
    I.processing_date,
    I.balance,
    I.eligible_tag,
    V_REWARD,
    I.transaction_id,
    I.payee_name,
    V_REMARKS,
    V_FLAG,
    I.as_of_month,
    I.product_name,
    I.product_capping,
    I.CUSTOMER_SEGMENT,
    I.RD_ACCOUNT_NBR,
    I.MEMBER_CUST_ID);
    END IF;
    COMMIT;
    ELSE
    V_REMARKS := i.remarks;
    -- V_REMARKS := i.PRODUCT_NAME ||'transaction successfully earned'||' '||0 ;
    V_FLAG := 'R';
    INSERT INTO LY_RWPT_CAP_SUCCESS
    VALUES
    (I.source_account_number,
    I.cust_id,
    I.customer_status_code,
    I.product_code,
    I.value,
    I.transaction_date,
    I.processing_date,
    I.balance,
    I.eligible_tag,
    0,
    I.transaction_id,
    I.payee_name,
    V_REMARKS,
    V_FLAG,
    I.as_of_month,
    I.product_name,
    I.product_capping,
    I.CUSTOMER_SEGMENT,
    I.RD_ACCOUNT_NBR,
    I.MEMBER_CUST_ID);
    END IF;
    COMMIT;
    END LOOP;
    END;

    Try this
    create or replace procedure ly_product_capping_old
       p_month varchar2
    is
    begin
       insert
         into ly_rwpt_cap_success
       select i.source_account_number,
              i.cust_id,
              i.customer_status_code,
              i.product_code,
              i.value,
              i.transaction_date,
              i.processing_date,
              i.balance,
              i.eligible_tag,
              case when i.reward != 0 then
                      case when nvl(j.rewards, 0) >  i.product_capping then 0
                        when nvl(j.rewards, 0) =  0 and i.rewards <= i.product_capping then i.rewards
                     when i.product_capping <  nvl(j.rewards, 0) + i.rewards then abs(i.product_capping -  nvl(j.rewards, 0))
                     when i.product_capping >= nvl(j.rewards, 0) + i.rewards then i.rewards
                   end
                   else 0
              end v_reward,
              i.transaction_id,
              i.payee_name,
              case when i.reward != 0 then
                      case when nvl(j.rewards, 0) >  i.product_capping then i.remarks || ' but receiving ' || ' ' || 0 || ' points as reached to product capping'
                        when nvl(j.rewards, 0) =  0 and i.rewards <= i.product_capping then i.remarks
                     when i.product_capping <  nvl(j.rewards, 0) + i.rewards then i.remarks || ' but earned  ' || ' ' || abs(i.product_capping -  nvl(j.rewards, 0)) || ' partial  points' || ' as exceeding product capping';
                     when i.product_capping >= nvl(j.rewards, 0) + i.rewards then i.remarks
                   end
                else i.remarks
              end  v_remarks,
              case when i.reward != 0 then
                      case when nvl(j.rewards, 0) >  i.product_capping then 'N'
                        when nvl(j.rewards, 0) =  0 and i.rewards <= i.product_capping then 'F'
                     when i.product_capping <  nvl(j.rewards, 0) + i.rewards then 'P'
                     when i.product_capping >= nvl(j.rewards, 0) + i.rewards then 'F'
                   end
                else 'R'
              end v_flag,
              i.as_of_month,
              i.product_name,
              i.product_capping,
              i.customer_segment,
              i.rd_account_nbr,
              i.member_cust_id
         from ly_rwpt_success i
         left
         join (
                 select product_code, source_account_number, sum(rewards) rewards
                   from ly_rwpt_cap_success
                  where as_of_month  = p_month
                    and partial_flag in ('F', 'P')
                  group
                     by product_code, source_account_number
              ) j
           on i. product_code = j.product_code
          and i.source_account_number = j.source_account_number
        where as_of_month = p_month;
       commit;
    end;There could be some semantic errors, if found please correct. And also please specify the column list in the insert statement.
    And oh forgot to mention the code is untested :)

  • Please optimize the query

    Hi,
    I have a query that will select the same tables and using Subquery. The query is taking too much time as the table has more records. Can anyone help to modify the query which can take minimum time. Thanks in Advance.
    Below is the query
    SELECT
    SIK_ROLLE_ID,SIK_OBJEKT_ID,SIK_AFTALE_ID,SIK_AFTALE_TP,ROLLE_TP,KNID,EJENDOMS_ID,EJENDOMS_TP, VURD_BLB
    ,VURD_VAKD,VURD_DT,HAIRCUT,SIK_VAKD,SIK_FOER_BLB,HAIRCUT_BLB,FORANST_PRIO_BLB,RETTIGHEDER_BLB,SIK_EFTER_BLB
    ,OVERSKREVET_MK,OVERSKREVET_BLB,MAN_HAIRCUT_BLB,MAN_OBJ_E_HCUT_BLB,GLDER_FRA_DT, TRANSAKTIONS_TP,SIK_STATUS_TP
    FROM
    ETZ3EDW.dbo.EWWH_KS_OBJ_KND2_HV A
    WHERE
    A.SIK_AFTALE_TP = 20130 and A.TRANSAKTIONS_TP not in ('S')
    AND A.GLDER_FRA_DT = ( SELECT MAX(B.GLDER_FRA_DT)
    FROM ETZ3EDW.DBO.EWWH_KS_OBJ_KND2_HV B
    WHERE B.GLDER_FRA_DT <= '2014-01-08'
    AND A.SIK_OBJEKT_ID = B.SIK_OBJEKT_ID
    AND A.SIK_AFTALE_ID = B.SIK_AFTALE_ID)

    Can you show us a execution plan of the query?
    CREATE TABLE #tmp (col DATE)
    INSERT INTO #tmp
    SELECT MAX(B.GLDER_FRA_DT)
    FROM ETZ3EDW.DBO.EWWH_KS_OBJ_KND2_HV BJOIN ETZ3EDW.dbo.EWWH_KS_OBJ_KND2_HV AON A.SIK_OBJEKT_ID = B.SIK_OBJEKT_ID
    AND A.SIK_AFTALE_ID = B.SIK_AFTALE_ID
    WHERE B.GLDER_FRA_DT <= '2014-01-08'SELECT
    SIK_ROLLE_ID,SIK_OBJEKT_ID,SIK_AFTALE_ID,SIK_AFTALE_TP,ROLLE_TP,KNID,EJENDOMS_ID,EJENDOMS_TP, VURD_BLB
    ,VURD_VAKD,VURD_DT,HAIRCUT,SIK_VAKD,SIK_FOER_BLB,HAIRCUT_BLB,FORANST_PRIO_BLB,RETTIGHEDER_BLB,SIK_EFTER_BLB
    ,OVERSKREVET_MK,OVERSKREVET_BLB,MAN_HAIRCUT_BLB,MAN_OBJ_E_HCUT_BLB,GLDER_FRA_DT, TRANSAKTIONS_TP,SIK_STATUS_TP
    FROM
    ETZ3EDW.dbo.EWWH_KS_OBJ_KND2_HV A
    WHERE
    A.SIK_AFTALE_TP = 20130 and A.TRANSAKTIONS_TP not in ('S')
    AND A.GLDER_FRA_DT IN (SELECT col FROM #tmp)
    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

  • Can anyone tell me how can i optimize this query...

    Can anyone tell me how can i optimize this query ??? :
    Select Distinct eopersona.numident From rscompeten , rscompet , rscv , eopersona , rscurso , rseduca , rsexplab , rsinteres
    Where ( ( (LOWER (rscompeten.nombre LIKE '%caracas%') AND ( rscompeten.id = rscompet.idcompeten ) AND ( rscv.id = rscompet.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rscurso.nombre) LIKE '%caracas%') AND ( rscv.id = rscurso.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rscurso.lugar) LIKE '%caracas%') AND ( rscv.id = rscurso.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rseduca.univinst) LIKE '%caracas%)' AND ( rscv.id = rseduca.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rsexplab.nombempre) LIKE '%caracas%' AND ( rscv.id = rsexplab.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rsinteres.descrip) LIKE '%caracas%' AND ( rscv.id = rsinteres.idcv ) AND ( eopersona.id = rscv.idpersona ) )
    OR ( (LOWER (rscv.cargoasp) LIKE '%caracas%' AND ( eopersona.id = rscv.idpersona ) )
    OR ( LOWER (eopersona.ciudad) LIKE '%caracas%' AND ( eopersona.id = rscv.idpersona )
    PLEASE IF YOU FIND SOMETHING WRONG.. PLEASE HELP ME.. this query takes me aproximatelly 10 minutes and the database is really small ( with only 200 records on each table )

    You are querying eight tables, however in any of your OR predicates you're only restricting 3 or 4 of those tables. That means that the remaining 4 or 5 tables are generating cartesian products. (n.b. the cartesian product of 5 tables with 200 rows each results in g 200^5 = 320,000,000,000 rows) Then you casually hide this behind "distinct".
    A simple restatement of your requirements looks like this:
    Select eopersona.numident
      From rscompeten,
           rscompet,
           rscv,
           eopersona
    Where LOWER (rscompeten.nombre) LIKE '%caracas%'
       AND rscompeten.id = rscompet.idcompeten
       AND rscv.id = rscompet.idcv
       AND eopersona.id = rscv.idpersona
    UNION
    Select eopersona.numident
      From rscurso ,
           rscv,
           eopersona
    Where LOWER (rscurso.nombre) LIKE '%caracas%'
       AND rscv.id = rscurso.idcv
       AND eopersona.id = rscv.idpersona
    UNION
    Select eopersona.numident
      From rscurso ,
           rscv,
           eopersona
    Where LOWER (rscurso.lugar) LIKE '%caracas%'
       AND rscv.id = rscurso.idcv
       AND eopersona.id = rscv.idpersona
    UNION
    ...From there you can eliminate redundancies as desired, but I imagine that the above will perform admirably with the data volumes you describe.

  • Help needed for writing query

    help needed for writing query
    i have the following tables(with data) as mentioned below
    FK*-foregin key (SUBJECTS)
    FK**-foregin key (COMBINATION)
    1)SUBJECTS(table name)     
    SUB_ID(NUMBER) SUB_CODE(VARCHAR2) SUB_NAME (VARCHAR2)
    2           02           Computer Science
    3           03           Physics
    4           04           Chemistry
    5           05           Mathematics
    7           07           Commerce
    8           08           Computer Applications
    9           09           Biology
    2)COMBINATION
    COMB_ID(NUMBER) COMB_NAME(VARCHAR2) SUB_ID1(NUMBER(FK*)) SUB_ID2(NUMBER(FK*)) SUB_ID3(NUMBER(FK*)) SUBJ_ID4(NUMBER(FK*))
    383           S1      9           4           2           3
    384           S2      4           2           5           3
    ---------I actually designed the ABOVE table also like this
    3) a)COMBINATION
    COMB_ID(NUMBER) COMB_NAME(VARCHAR2)
    383           S1
    384           S2
    b)COMBINATION_DET
    COMBDET_ID(NUMBER) COMB_ID(FK**) SUB_ID(FK*)
    1               383          9
    2               383          4
    3               383          2
    4               383          3
    5               384          4
    6               384          2          
    7               384          5
    8               384          3
    Business rule: a combination consists of a maximum of 4 subjects (must contain)
    and the user is less relevant to a COMB_NAME(name of combinations) but user need
    the subjects contained in combinations
    i need the following output
    COMB_ID COMB_NAME SUBJECT1 SUBJECT2      SUBJECT3      SUBJECT4
    383     S1     Biology Chemistry      Computer Science Physics
    384     S2     Chemistry Computer Science Mathematics Physics
    or even this is enough(what i actually needed)
    COMB_ID     subjects
    383           Biology,Chemistry,Computer Science,Physics
    384           Chemistry,Computer Science,Mathematics,Physics
    you can use any of the COMBINATION table(either (2) or (3))
    and i want to know
    1)which design is good in this case
    (i think SUB_ID1,SUB_ID2,SUB_ID3,SUB_ID4 is not a
    good method to link with same table but if 4 subjects only(and must) comes
    detail table is not neccessary )
    now i am achieving the result by program-coding in C# after getting the rows from oracle
    i am using oracle 9i (also ODP.NET)
    i want to know how can i get the result in the stored procedure itsef.
    2)how it could be designed in any other way.
    any help/suggestion is welcome
    thanks for your time --Pradeesh

    Well I forgot the table-alias, here now with:
    SELECT C.COMB_ID
    , C.COMB_NAME
    , (SELECT SUB_NAME
    FROM SUBJECTS
    WHERE SUB_ID = C.SUB_ID1) AS SUBJECT_NAME1
    , (SELECT SUB_NAME
    FROM SUBJECTS
    WHERE SUB_ID = C.SUB_ID2) AS SUBJECT_NAME2
    , (SELECT SUB_NAME
    FROM SUBJECTS
    WHERE SUB_ID = C.SUB_ID3) AS SUBJECT_NAME3
    , (SELECT SUB_NAME
    FROM SUBJECTS
    WHERE SUB_ID = C.SUB_ID4) AS SUBJECT_NAME4
    FROM COMBINATION C;
    As you need exactly 4 subjects, the columns-solution is just fine I would say.

  • HELP TO TUNE THIS QUERY

    Hi,
    I'm using below query in procedure.It's taking more more time can some one help to tune this query or advice to rewrite the query.
    Databse :10.1
    SELECT   'Reading Comprehension' TEST_NAME,T.TEST_END_DATE TEST_SESSION_DATE,
            C.POOL_VERSION_ID, I.CREATED_ON POOL_CREATED_DT,
            C.ITEM_ID, C.ITEM_RESPONSE_ID, S.STUDENT_ID_PK, C.RESPONSE_KEY, C.IS_CORRECT RESPONSE_IS_CORRECT,
            T.SCORE SCALE_SCORE, C.RESPONSE_DURATION, P.ITEM_KEY,
            T.TEST_SESSION_DETAIL_ID, SYSDATE CREATED_ON
           -- BULK COLLECT INTO TV_PSYCHO_DET
            FROM
            CAT_ITEM_PARAMETER P, CAT_ITEM_USER_RESPONSE C, TEST_SESSION_DETAIL T,
            TEST_SESSION S, ITEM_POOL_VERSION I, TEST_DETAIL D
            ,INSTITUTION E
            WHERE  TRUNC(T.TEST_END_DATE) BETWEEN TO_DATE('01-11-09','dd-mm-yy') AND TO_DATE('30-11-09','dd-mm-yy')
            AND D.TEST_NAME =  'Reading Comprehension'
            AND T.TEST_SESSION_STATUS_ID = 3
            AND I.POOL_AVAILABILITY='Y'
            AND P.PRETEST=0 AND C.RESTART_FLAG=0
            AND T.TEST_DETAIL_ID = D.TEST_DETAIL_ID
            AND S.TEST_SESSION_ID = T.TEST_SESSION_ID
            AND C.TEST_SESSION_DETAIL_ID = T.TEST_SESSION_DETAIL_ID
            AND S.INSTITUTION_ID=E.INSTITUTION_ID
            AND SUBSTR(E.INSTITUTION_ID_DISPLAY,8,3) <> '000'
            AND I.ITEM_ID = C.ITEM_ID
            AND P.ITEM_ID = I.ITEM_ID;expln plan
    Plan hash value: 3712814491                                                                                                      
    | Id  | Operation                                 | Name                        | Rows  | Bytes | Cost (%CPU)| Time     | Pstart|
    Pstop |                                                                                                                          
    |   0 | SELECT STATEMENT                          |                             | 50857 |  7151K| 93382   (1)| 00:18:41 |       |
          |                                                                                                                          
    |*  1 |  FILTER                                   |                             |       |       |            |          |       |
          |                                                                                                                          
    |*  2 |   HASH JOIN                               |                             | 50857 |  7151K| 93382   (1)| 00:18:41 |       |
          |                                                                                                                          
    |   3 |    PARTITION HASH ALL                     |                             |  2312 | 23120 |    25   (0)| 00:00:01 |     1 |
        5 |                                                                                                                          
    |*  4 |     TABLE ACCESS FULL                     | CAT_ITEM_PARAMETER          |  2312 | 23120 |    25   (0)| 00:00:01 |     1 |
        5 |                                                                                                                          
    |*  5 |    HASH JOIN                              |                             | 94938 |    12M| 93356   (1)| 00:18:41 |       |
          |                                                                                                                          
    |*  6 |     TABLE ACCESS FULL                     | ITEM_POOL_VERSION           |  9036 |   132K|    30   (0)| 00:00:01 |       |
          |                                                                                                                          
    |*  7 |     TABLE ACCESS BY GLOBAL INDEX ROWID    | CAT_ITEM_USER_RESPONSE      |     9 |   279 |    18   (0)| 00:00:01 | ROWID |
    ROWID |                                                                                                                          
    |   8 |      NESTED LOOPS                         |                             | 45349 |  5270K| 93325   (1)| 00:18:40 |       |
          |                                                                                                                          
    |*  9 |       HASH JOIN                           |                             |  4923 |   423K| 11377   (1)| 00:02:17 |       |
          |                                                                                                                          
    |* 10 |        INDEX FAST FULL SCAN               | INSTI_ID_NAME_COUN_DISP_IDX |  8165 |   111K|    18   (0)| 00:00:01 |       |
          |                                                                                                                          
    |* 11 |        HASH JOIN                          |                             |  4923 |   355K| 11359   (1)| 00:02:17 |       |
          |                                                                                                                          
    |* 12 |         TABLE ACCESS BY GLOBAL INDEX ROWID| TEST_SESSION_DETAIL         |  4107 |   148K|  6804   (1)| 00:01:22 | ROWID |
    ROWID |                                                                                                                          
    |  13 |          NESTED LOOPS                     |                             |  4923 |   278K|  6806   (1)| 00:01:22 |       |
          |                                                                                                                          
    |* 14 |           INDEX RANGE SCAN                | TEST_DETAIL_AK_1            |     1 |    21 |     2   (0)| 00:00:01 |       |
          |                                                                                                                          
    |* 15 |           INDEX RANGE SCAN                | TEST_SESSION_DETAIL_FK2_I   | 39737 |       |   102   (0)| 00:00:02 |       |
          |                                                                                                                          
    |  16 |         PARTITION HASH ALL                |                             |  1672K|    25M|  4546   (1)| 00:00:55 |     1 |
        5 |                                                                                                                          
    |  17 |          TABLE ACCESS FULL                | TEST_SESSION                |  1672K|    25M|  4546   (1)| 00:00:55 |     1 |
        5 |                                                                                                                          
    |* 18 |       INDEX RANGE SCAN                    | CAT_ITEM_USER_RESP_IDX1     |    18 |       |     3   (0)| 00:00:01 |       |
          |                                                                                                                          
    Predicate Information (identified by operation id):                                                                              
       1 - filter(TO_DATE('01-11-09','dd-mm-yy')<=TO_DATE('30-11-09','dd-mm-yy'))                                                    
       2 - access("P"."ITEM_ID"="I"."ITEM_ID")                                                                                       
       4 - filter("P"."PRETEST"=0)                                                                                                   
       5 - access("I"."ITEM_ID"="C"."ITEM_ID")                                                                                       
       6 - filter("I"."POOL_AVAILABILITY"='Y')                                                                                       
       7 - filter(TO_NUMBER("C"."RESTART_FLAG")=0)                                                                                   
       9 - access("S"."INSTITUTION_ID"="E"."INSTITUTION_ID")                                                                         
      10 - filter(SUBSTR("E"."INSTITUTION_ID_DISPLAY",8,3)<>'000')                                                                   
      11 - access("S"."TEST_SESSION_ID"="T"."TEST_SESSION_ID")                                                                       
      12 - filter(TRUNC(INTERNAL_FUNCTION("T"."TEST_END_DATE"))>=TO_DATE('01-11-09','dd-mm-yy') AND "T"."TEST_SESSION_STATUS_ID"=3   
                  AND TRUNC(INTERNAL_FUNCTION("T"."TEST_END_DATE"))<=TO_DATE('30-11-09','dd-mm-yy'))                                 
      14 - access("D"."TEST_NAME"='Reading Comprehension')                                                                           
      15 - access("T"."TEST_DETAIL_ID"="D"."TEST_DETAIL_ID")                                                                         
      18 - access("C"."TEST_SESSION_DETAIL_ID"="T"."TEST_SESSION_DETAIL_ID")                                                         
    43 rows selected.Edited by: user575115 on Dec 18, 2009 12:31 AM

    When you see something like ...
       7 - filter(TO_NUMBER("C"."RESTART_FLAG")=0)                                                                                    It means that Oracle had to do a conversion for you since you aren't using the proper data type in your query.
    That would mean IF there is an index on that column, it won't be useable...

  • Need help in the sql query

    i have a table
    source table :
    create table order(name_a varchar2(100),intid number);
    insert into order values('a',1);
    insert into order values('b',1);
    insert into order values('c',1);
    insert into order values('d',1);
    insert into order values('e',2);
    insert into order values('f',2);
    insert into order values('g',2);
    i need a query , which result in the below output :
    if i look for intid=1 the query should give a,b,c,d
    if i look for intid=2 the query should give f,g
    Thanks

    Hi,
    781649 wrote:
    i have a table
    source table :
    create table order(name_a varchar2(100),intid number);
    insert into order values('a',1);
    insert into order values('b',1);
    insert into order values('c',1);
    insert into order values('d',1);
    insert into order values('e',2);
    insert into order values('f',2);
    insert into order values('g',2);Thanks for posting the CREATE TABLE and INSERT statements; it's very helpful.
    i need a query , which result in the below output :
    if i look for intid=1 the query should give a,b,c,d
    if i look for intid=2 the query should give f,gDid you mean <b>e</b>,f,g ?
    That's called String Aggregation , and how to do it depends on your version of Oracle, and your exact requirements.
    See thie following page for several techniques:
    http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
    If you're using Oracle 10 (or higher), and it's important that the name_a's be in order in the output, then you can do this:
    WITH     got_r_num     AS
         SELECT     name_a
         ,     intid
         ,     ROW_NUMBER () OVER ( PARTITION BY  intid
                                   ORDER BY          name_a
                           )         AS r_num
         FROM     order_table                    -- ORDER is not a good table name
         WHERE     intid     IN (1)                    -- Optional
    SELECT     intid
    ,     SUBSTR ( SYS_CONNECT_BY_PATH (name_a, ',')
                , 2
                )     AS name_a_list
    FROM     got_r_num
    WHERE     CONNECT_BY_ISLEAF     = 1
    START WITH     r_num     = 1
    CONNECT BY     r_num     = PRIOR r_num + 1
         AND     intid     = PRIOR intid
    ;Starting in Oracle 11.2, LISTAGG is better.
    This does not assume that you are getting the output only for a single intid at a time. You can get any number of them in a suingle query. Of course, that number can be 1 if that's what you want.
    Edited by: Frank Kulash on Mar 24, 2011 12:19 PM

Maybe you are looking for