Help Tunning (PLSQL)

Hi All,
i have this Table (example table with example data)
  CREATE TABLE "TB_GEN_PRODUCTO_TEMP"
  ("ID_PRODUCTO" NUMBER,
  "COD_CODIGO" CHAR(8),
  "DES_NOMBRE" VARCHAR2(128));
  CREATE UNIQUE INDEX "TB_GEN_PRODUCTO_TEMP_PK" ON "TB_GEN_PRODUCTO_TEMP" ("ID_PRODUCTO")
  ALTER TABLE "TB_GEN_PRODUCTO_TEMP" ADD CONSTRAINT "TB_GEN_PRODUCTO_TEMP_PK" PRIMARY KEY ("ID_PRODUCTO") ENABLE
Insert into TB_GEN_PRODUCTO_TEMP (ID_PRODUCTO,COD_CODIGO,DES_NOMBRE) values ('16957','10103696','CHORIZO PARRILLERO DG');
Insert into TB_GEN_PRODUCTO_TEMP (ID_PRODUCTO,COD_CODIGO,DES_NOMBRE) values ('16958','10103697','QUESO AZUL CHILI''S');
Insert into TB_GEN_PRODUCTO_TEMP (ID_PRODUCTO,COD_CODIGO,DES_NOMBRE) values ('16959','10104001','ACEITUNA NEGRA');
Insert into TB_GEN_PRODUCTO_TEMP (ID_PRODUCTO,COD_CODIGO,DES_NOMBRE) values ('16960','10104002','ACEITUNA VERDE');
Insert into TB_GEN_PRODUCTO_TEMP (ID_PRODUCTO,COD_CODIGO,DES_NOMBRE) values ('16961','10104003','AJI PANCA A GRANEL');
  CREATE TABLE "TB_INV_KARDEX_TEMP"
  ("ID_KARDEX" NUMBER,
  "ID_ALMACEN" NUMBER,
  "ID_PRODUCTO" NUMBER,
  "CTD_INV_INI" NUMBER(12,6),
  "CTD_ENTRADA" NUMBER(12,6),
  "CTD_SALIDA" NUMBER(12,6),
  "CTD_INV_FIN" NUMBER(12,6),
  "MTO_COST_INI" NUMBER(12,6),
  "MTO_COST_TRANS" NUMBER(12,6),
  "MTO_COST_FIN" NUMBER(12,6),
  "ID_MOT_TRANS" NUMBER,
  "FCH_FECHA_HORA" TIMESTAMP (6),
  "NUM_TRANSAC" VARCHAR2(16))
  CREATE UNIQUE INDEX "TB_INV_KARDEX_TEMP_PK" ON "TB_INV_KARDEX_TEMP" ("ID_KARDEX")
  ALTER TABLE "TB_INV_KARDEX_TEMP" ADD CONSTRAINT "TB_INV_KARDEX_TEMP_PK" PRIMARY KEY ("ID_KARDEX") ENABLE;
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('144','191','16945','8890','0','90','8800','0,5824','0,5824','0,5824','101',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'13');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('145','191','16946','10447','0','70','10377','1,2665','1,2665','1,2665','101',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'13');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('146','191','16665','5242','2','0','5244','0,284','0,284','0,284','252',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'14');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('147','194','17008','0','80','0','80','0','1,9514','1,9514','201',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'15');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('148','194','18109','0','3','0','3','0','8,2','8,2','201',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'15');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('149','191','17008','602','0','80','522','1,9514','1,9514','1,9514','101',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'16');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('150','191','18109','10','0','3','7','8,2','8,2','8,2','101',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'16');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('151','191','16665','5284','5500','0','10784','0,284','0,284','0,284','305',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'17');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('152','191','18109','7','1000','0','1007','8,2','8,2','8,2','305',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'18');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('153','194','18106','0','5','0','5','0','8,7214','8,7214','201',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'19');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('154','191','18106','140','0','5','135','8,7214','8,7214','8,7214','101',to_timestamp('02/09/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'20');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('164','193','17234','166,14','4','0','170,14','3,5455','3,5455','3,5455','305',to_timestamp('16/10/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'23');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('162','193','16957','55','4','0','59','0,9818','0,9818','0,9818','305',to_timestamp('16/10/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'21');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('318','192','18100','75,6','0','0,06','75,54','10,1389','10,1389','10,1389','152',to_timestamp('18/08/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'76');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('319','192','18183','100','0','0,015','99,985','11,0167','11,0167','11,0167','152',to_timestamp('18/08/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'76');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('320','192','17769','88,0225','0','0,006','88,0165','2,7035','2,7035','2,7035','152',to_timestamp('18/08/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'76');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('321','192','17894','192,0609','0','0,018','192,0429','5,4437','5,4437','5,4437','152',to_timestamp('18/08/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'76');
Insert into TB_INV_KARDEX_TEMP (ID_KARDEX,ID_ALMACEN,ID_PRODUCTO,CTD_INV_INI,CTD_ENTRADA,CTD_SALIDA,CTD_INV_FIN,MTO_COST_INI,MTO_COST_TRANS,MTO_COST_FIN,ID_MOT_TRANS,FCH_FECHA_HORA,NUM_TRANSAC) values ('322','192','17939','252,0519','0','0,018','252,0339','2,9356','2,9356','2,9356','152',to_timestamp('18/08/12 00:00:00,000000000','DD/MM/RR HH24:MI:SS,FF'),'76');
-- AND 2 FUNCTIONS
create or replace
FUNCTION "FN_INV_CANT_FIN_PRODUCT_ALM_T"
intIdProducto number,
intIdAlmacen NUMBER,
fchFechaInicial DATE,
fchFechaFinal DATE
return number
is
  datCantidad_Final number;
begin
  select ctd_inv_fin into datCantidad_Final from (
  select NVL(ctd_inv_fin,0) as ctd_inv_fin
  from TB_INV_KARDEX_TEMP where id_producto=intIdProducto
  AND id_almacen=intIdAlmacen
  AND  FCH_FECHA_HORA >=fchFechaInicial and FCH_FECHA_HORA< fchFechaFinal
  and  id_mot_trans in (201,202,208,209,210,211,213,101,102,108,109,110,111,113)
  order by FCH_FECHA_HORA,NUM_TRANSAC DESC)
  where rownum=1;
return (datCantidad_Final);
end;
create or replace
FUNCTION "FN_INV_CANT_INI_PRODUCTO_ALM_T"
intIdProducto number,
intIDAlmacen NUMBER,
fchFechaInicial DATE,
fchFechaFinal DATE
return number
is
  datCantidad_Inicial number(8,2);
begin
    select ctd_inv_ini into  datCantidad_Inicial  from (
     select NVL(ctd_inv_ini,0) as ctd_inv_ini
      from TB_INV_KARDEX_TEMP where id_producto=intIdProducto
      and id_almacen=intIDAlmacen
       AND  FCH_FECHA_HORA >=fchFechaInicial and FCH_FECHA_HORA< fchFechaFinal
      and  id_mot_trans in (201,202,208,209,210,211,213,101,102,108,109,110,111,113)
        order by num_transac)
  where rownum=1;
return (datCantidad_Inicial);
end;OK, with that data example i do this select statement on PLSQL..
SELECT
a.ID_ALMACEN,
a.id_producto as "Id_Producto" ,
substr(b.des_nombre,0,20) as "Des_Producto",
( SUM(NVL(cvi.CTD_ENTRADA,0)) - SUM(NVL(cvs.CTD_SALIDA,0)) ) as "Cant_Ventas" ,
( SUM(NVL(cdi.CTD_ENTRADA,0)) - SUM(NVL(cds.CTD_SALIDA,0)) )as "Cant_Desechos" ,
(NVL((SELECT FN_INV_CANT_INI_PRODUCTO_ALM_T(a.id_producto, a.id_almacen, SYSDATE-30,SYSDATE) from dual),0) -
NVL((SELECT FN_INV_CANT_FIN_PRODUCT_ALM_T(a.id_producto, a.id_almacen, SYSDATE-30,SYSDATE) from dual),0)
)  as "Cant_Real",
0   as "Cost_Real",
  SELECT NVL(SUM(ti.MTO_MONTO_NETO),0)
  FROM tb_vta_ticket_venta ti
  WHERE ti.id_almacen = a.id_almacen
  --AND ti.FCH_FECHA_HORA >=datFechaInicial and ti.FCH_FECHA_HORA< datFechaFinal
  ) as "Venta_Neta"
FROM TB_INV_KARDEX_TEMP a 
INNER JOIN TB_GEN_PRODUCTO_TEMP b on a.id_producto = b.id_producto
LEFT JOIN TB_INV_KARDEX_TEMP cpi on a.id_kardex = cpi.id_kardex and cpi.id_mot_trans = 251
LEFT JOIN TB_INV_KARDEX_TEMP cdi on a.id_kardex = cdi.id_kardex and cdi.id_mot_trans = 250
LEFT JOIN TB_INV_KARDEX_TEMP cvi on a.id_kardex = cvi.id_kardex and cvi.id_mot_trans in (207,253,214,252,254,255,256)
LEFT JOIN TB_INV_KARDEX_TEMP cds on a.id_kardex = cds.id_kardex and cds.id_mot_trans = 150
LEFT JOIN TB_INV_KARDEX_TEMP cps on a.id_kardex = cps.id_kardex and cps.id_mot_trans = 151
LEFT JOIN TB_INV_KARDEX_TEMP cvs on a.id_kardex = cvs.id_kardex and cvs.id_mot_trans in (107,153,114,152,154,155,156)
WHERE
a.FCH_FECHA_HORA >= SYSDATE-30 and a.FCH_FECHA_HORA < SYSDATE
GROUP BY  
  a.ID_ALMACEN,  a.id_producto,  b.des_nombre;the reason i use multiples left join to same table, its because i need specific values on id_mot_trans, so i need to tuning it for the better perfomance, i hope anyone can help me, the tables structure is an example of the real data.
Thanks for the help and time.
Edited by: xDeviates on 09-nov-2012 8:01

Hi xDeviates,
The first approach should be the one stated above by jihuyao
>
Avoid using any pl/sql function in sql if possible.
>
as it seems, that both of your functions work as something like a subselect you may try to rephrase your statement according to this idea.
Another idea could be an index on
INV_KARDEX_TEMP.id_mot_trans
BUT* this has to be tested. Indexes don't solve all perfomance issues. For me it's just a try, because I don't wholly know your database (setup, design, ...).
If nothing of this helps I would like to take a look at the EXECUTION PLAN of your query to see how it works right now and where possible problems might occur.
Regards
Oli
Edited by: stratmo on Nov 12, 2012 2:14 AM

Similar Messages

  • 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  ....

  • How to tune plsql code

    hi all,
    tell me any one how to tune the plsql code in oracle plsql

    You could have googled a bit ->
    http://www.google.co.in/#hl=en&q=tuning+pl+sql+in+oracle&meta=&aq=&oq=tuning+pl+sql+in+oracle&fp=3c5f05f17abf6d93
    Regards.
    Satyaki De.

  • Ugent: I need help with plsql:

    Some body helps me to do the following updated using plsql:
    I have two tables, xx_firm and xx_contact, related by “firm_seq”; one to many.
    The xx.contact has the following fields:
    cntc_firm_seq
    cntc_title_desc
    cntc_aap_contact
    were firm_seq (from xx_firm) is equal to cntc_firm_seq. Meaning that a firm can have one or many contacts, but one of this contacts must be storage the value “765”.
    I need able to update the field “cntc_title_desc” to 765 only if not of its contacts have that value.
    Thanks,

    there is an error in my sql and hope you may be able to spot it:
    update xx_contact c
    set cntc_title_desc='756'
    where cntc_firm_seq =(select f.firm_seq --was c.firm_seq
    from xx_firm f
    where f.firm_seq = c.cntc_firm_seq
    and c.cntc_title_desc <> '765';

  • Help with PLSQL table population.....

    Hi all,
    I am populating a PLSQL table from a cursor and then inserting into a target table using FORALL.
    While populating, I need two two records differing only by the process_name.
    Say my populated PLSQL table should look like this.
    vt_proc_status_tbl:
    1     76     Pname_A     20     Sysdate     1     U     1
    1     76     Pname_B     20     Sysdate     1     U     1
    How can I create duplicate records like this inside the PLSQL table varying only by process_name????
    OPEN cur_fcst_sites_ppo;
    FETCH cur_fcst_sites_ppo
    BULK COLLECT INTO vt_fcst_sites_tbl;
    CLOSE cur_fcst_sites_ppo;
    FOR v_idx_fcst_sites IN 1 .. vt_fcst_sites_tbl.COUNT
    LOOP
    BEGIN
    SELECT seq_ods_site_process_status.NEXTVAL
    INTO v_odssiteprocessid
    FROM DUAL;
    END;
    v_pst_idx := v_pst_idx + 1;
    vt_proc_status_tbl (v_pst_idx).odssiteprocessid :=
    v_odssiteprocessid;
    vt_proc_status_tbl (v_pst_idx).SYSTEM := pi_system;
    vt_proc_status_tbl (v_pst_idx).process_name := pi_process_name;
    vt_proc_status_tbl (v_pst_idx).siteid :=
    vt_fcst_sites_tbl (v_idx_fcst_sites).siteid;
    vt_proc_status_tbl (v_pst_idx).bday := pi_transferday;
    vt_proc_status_tbl (v_pst_idx).is_no := pi_is_no;
    vt_proc_status_tbl (v_pst_idx).rest_status := c_status_unprocessed;
    vt_proc_status_tbl (v_pst_idx).batch_id := v_batch_id;
    v_cntr := v_cntr + 1;
    IF v_cntr = pi_sites_at_a_time
    THEN
    v_batch_id := v_batch_id + 1;
    v_cntr := 0;
    END IF;
    v_odssiteprocessid := NULL;
    END LOOP;
    IF v_pst_idx &gt; 0
    THEN
    BEGIN
    FORALL v_proc_status_tbl_idx IN 1 .. vt_proc_status_tbl.COUNT
    INSERT INTO ods_site_process_status
    VALUES vt_proc_status_tbl (v_proc_status_tbl_idx);
    END;
    ELSE
    v_code := NULL;
    SELECT SUBSTR ( '[M]:0- No Site Available for the '
    || pi_process_name
    || ' Process For '
    || DECODE (pi_process_name,
    c_transform_bmi_ppo, 'IS_NO '
    || pi_is_no,
    'TransferDay ' || pi_transferday
    || '..',
    1,
    125
    INTO v_errm
    FROM DUAL;
    DBMS_OUTPUT.put_line (v_errm);
    scimf_common.write_log (v_code, --Log error into the LOGFILE
    'E',
    'p_mfcst_transform_master',
    v_errm,
    vr_market.marketid,
    'I'
    END IF;
    Thanks in Advance.
    Jagadish
    Edited by: user646716 on Oct 12, 2008 10:08 AM
    Edited by: user646716 on Oct 12, 2008 12:02 PM

    hi aweiden,
    Please find my entire code below.
    what I am trying to achieve is that when my plsql table vt_proc_status_tbl is populated, I want two different rows to be populated for different process names (i.e bmi_ppo and bmi_ai ) and load it into ODS_SITE_PROCESS_STATUS table so that i do not have to alter my forall statement.
    Thanks for the help
    PROCEDURE p_mfcst_transform_master (
    pi_system IN mfcst_ppo.SYSTEM%TYPE,
    pi_is_ no IN mfcst_ppo.is_no%TYPE,
    pi_transferday IN mfcst_ppo.transferday%TYPE,
    pi_sites_at_a_time IN NUMBER,
    pi_process_name IN ods_site_process_status.process_name%TYPE,
    po_status OUT NUMBER,
    po_error OUT VARCHAR2
    AS
    -- Cursor to get sites to be processed for bmi to ppo transformation process
    CURSOR cur_fcst_sites_ppo
    IS
    SELECT DISTINCT siteid
    FROM sci_restaurant
    WHERE hist_load_status in ('L','H')
    AND SYSTEM = pi_system
    ORDER BY siteid;
    -- Cursor to get sites to be processed for bmi to ai transformation process
    -- Note this cursor is based on the system and transfer day
    TYPE sites_tbltype IS TABLE OF cur_fcst_sites_ppo%ROWTYPE
    INDEX BY PLS_INTEGER;
    vt_fcst_sites_tbl sites_tbltype;
    TYPE proc_status_tbltype IS TABLE OF ods_site_process_status%ROWTYPE
    INDEX BY PLS_INTEGER;
    vt_proc_status_tbl proc_status_tbltype;
    v_cnt NUMBER := 0;
    v_cntr NUMBER := 0;
    v_batch_id NUMBER := 1;
    v_pst_idx PLS_INTEGER := 0;
    v_k PLS_INTEGER := 0;
    v_odssiteprocessid ods_site_process_status.odssiteprocessid%TYPE;
    v_exceptionid NUMBER;
    --variable to log exception into sci_exception table
    BEGIN
    --- If sites were identitfied before, skip the rest of the execution
    --- Note that ods_site_process_status holds the status from the prior runs
    po_error := '';
    po_status := 0;
    scimf_common.p_get_market_parameters (NULL,
    pi_system,
    vr_market,
    v_error_out
    IF v_error_out IS NOT NULL
    THEN
    RAISE e_market_not_found;
    END IF;
    IF pi_process_name = c_transform_bmi_ppo
    THEN
    SELECT COUNT (*)
    INTO v_cnt
    FROM ods_site_process_status
    WHERE SYSTEM = pi_system
    AND process_name = pi_process_name
    AND is_no = pi_is_no
    AND ROWNUM < 2;
    ELSIF pi_process_name = c_transform_bmi_ai
    THEN
    SELECT COUNT (*)
    INTO v_cnt
    FROM ods_site_process_status
    WHERE SYSTEM = pi_system
    AND process_name = pi_process_name
    AND rest_status = c_status_processed
    AND ROWNUM < 2;
    ELSE
    v_code := NULL;
    v_errm :=
    SUBSTR ( '[E]:0- Process Name :>'
    || pi_process_name
    || '<Is Not Proper For System:>'
    || pi_system
    || '< and IS_NO :>'
    || pi_is_no
    || '< and TransferDay :>'
    || pi_transferday
    || '<',
    1,
    125
    DBMS_OUTPUT.put_line (v_errm);
    scimf_common.write_log (v_code, --Log error into the LOGFILE
    'E',
    'p_mfcst_transform',
    v_errm,
    vr_market.marketid,
    'I'
    po_error := TO_CHAR (SQLCODE) || ' -Error Message: ' || v_errm;
    po_status := -1;
    -- Log Exception in the log file and come out.
    END IF;
    IF NVL (v_cnt, 0) > 0
    THEN
    IF pi_process_name = c_transform_bmi_ppo
    THEN
    SELECT SUBSTR
    ( ':0- Sites are already identified before for the '
    || pi_process_name
    || ' Process For '
    || DECODE (pi_process_name,
    c_transform_bmi_ppo, 'IS_NO ' || pi_is_no,
    'TransferDay ' || pi_transferday
    || '..'
    || 'proceeding to invoke child scripts',
    1,
    125
    INTO v_errm
    FROM DUAL;
    DBMS_OUTPUT.put_line (v_errm);
    ELSIF pi_process_name = c_transform_bmi_ai
    THEN
    SELECT SUBSTR
    ( '[I]:0- Sites are already identified before for the '
    || pi_process_name
    || ' Process For '
    || DECODE (pi_process_name,
    c_transform_bmi_ai, 'IS_NO ' || pi_is_no,
    'TransferDay ' || pi_transferday
    || '..'
    || 'proceeding to invoke child scripts',
    1,
    125
    INTO v_errm
    FROM DUAL;
    DBMS_OUTPUT.put_line (v_errm);
    END IF;
    ELSIF NVL (v_cnt, 0) = 0
    THEN
    OPEN cur_fcst_sites_ppo;
    FETCH cur_fcst_sites_ppo
    BULK COLLECT INTO vt_fcst_sites_tbl;
    CLOSE cur_fcst_sites_ppo;
    END IF;
    -- Logic to batch the sites to be processed in the batches of
    -- sites derived from the pi_sites_at_a_time parameter
    -- Batch_Id starts with 1 and need to used along with
    -- either is_no (bmi-ppo) and process name or along with
    -- system, bday and process_name (bmi-ai)
    IF pi_sites_at_a_time IS NULL
    THEN
    v_code := NULL;
    v_errm := 'Site At A Time not defined';
    scimf_common.write_log (v_code, --Log error into the LOGFILE
    'E',
    'p_mfcst_transform_master',
    v_errm,
    vr_market.marketid,
    'I'
    po_error := TO_CHAR (SQLCODE) || ' -Error Message: ' || v_errm;
    po_status := -1;
    raise_application_error (-200002, v_errm);
    END IF;
    FOR v_idx_fcst_sites IN 1 .. vt_fcst_sites_tbl.COUNT
    LOOP
    BEGIN
    SELECT seq_ods_site_process_status.NEXTVAL
    INTO v_odssiteprocessid
    FROM DUAL;
    EXCEPTION
    WHEN OTHERS
    THEN
    ROLLBACK;
    DBMS_OUTPUT.put_line ( '[E]:0- Sequence :>'
    || 'seq_ods_site_process_status'
    || ' <Is Invalid>'
    || '<'
    v_errm :=
    SUBSTR ( 'Sequence seq_ods_site_process_status Error:'
    || SQLERRM,
    1,
    125
    scimf_common.write_log (v_code, --Log error into the LOGFILE
    'E',
    'p_mfcst_transform',
    v_errm,
    vr_market.marketid,
    'I'
    po_error :=
    TO_CHAR (SQLCODE) || ' -Error Message: '
    || v_errm;
    po_status := -1;
    raise_application_error (-200002, v_errm);
    END;
    v_pst_idx := v_pst_idx + 1;
    vt_proc_status_tbl (v_pst_idx).odssiteprocessid :=
    v_odssiteprocessid;
    vt_proc_status_tbl (v_pst_idx).SYSTEM := pi_system;
    vt_proc_status_tbl (v_pst_idx).process_name := pi_process_name;
    vt_proc_status_tbl (v_pst_idx).siteid :=
    vt_fcst_sites_tbl (v_idx_fcst_sites).siteid;
    vt_proc_status_tbl (v_pst_idx).bday := pi_transferday;
    vt_proc_status_tbl (v_pst_idx).is_no := pi_is_no;
    vt_proc_status_tbl (v_pst_idx).rest_status := c_status_unprocessed;
    vt_proc_status_tbl (v_pst_idx).batch_id := v_batch_id;
    v_cntr := v_cntr + 1;
    IF v_cntr = pi_sites_at_a_time
    THEN
    v_batch_id := v_batch_id + 1;
    v_cntr := 0;
    END IF;
    v_odssiteprocessid := NULL;
    END LOOP;
    IF v_pst_idx > 0
    THEN
    BEGIN
    FORALL v_proc_status_tbl_idx IN 1 .. vt_proc_status_tbl.COUNT
    INSERT INTO ods_site_process_status
    VALUES vt_proc_status_tbl (v_proc_status_tbl_idx);
    EXCEPTION
    WHEN OTHERS
    THEN
    ROLLBACK;
    v_error_count := SQL%BULK_EXCEPTIONS.COUNT;
    DBMS_OUTPUT.put_line
    ( '[E]:0- Bulk Insert Fail using FORALL Number of Failure:>'
    || v_error_count
    || '<'
    FOR v_i IN 1 .. v_error_count
    LOOP
    v_errm :=
    SUBSTR
    ( '[E]:Error Insert into ODS_SITE_PROCESS_STATUS table '
    || 'Insert Error: '
    || v_i
    || ' Array Index: '
    || SQL%BULK_EXCEPTIONS (v_i).ERROR_INDEX
    || SQLERRM
    (-SQL%BULK_EXCEPTIONS (v_i).ERROR_CODE),
    1,
    125
    DBMS_OUTPUT.put_line (v_errm);
    END LOOP;
    v_code := NULL;
    scimf_common.write_log (v_code, --Log error into the LOGFILE
    'E',
    'p_mfcst_transform_master',
    v_errm,
    vr_market.marketid,
    'I'
    po_error :=
    TO_CHAR (SQLCODE) || ' -Error Message: '
    || v_errm;
    po_status := -1;
    END;
    ELSE
    v_code := NULL;
    SELECT SUBSTR ( '[M]:0- No Site Available for the '
    || pi_process_name
    || ' Process For '
    || DECODE (pi_process_name,
    c_transform_bmi_ppo, 'IS_NO '
    || pi_is_no,
    'TransferDay ' || pi_transferday
    || '..',
    1,
    125
    INTO v_errm
    FROM DUAL;
    DBMS_OUTPUT.put_line (v_errm);
    scimf_common.write_log (v_code, --Log error into the LOGFILE
    'E',
    'p_mfcst_transform_master',
    v_errm,
    vr_market.marketid,
    'I'
    END IF;
    END IF;
    COMMIT;
    po_status := NVL (po_status, 0);
    EXCEPTION
    WHEN e_market_not_found
    THEN
    ROLLBACK;
    v_code := NULL;
    v_errm := SUBSTR ('[E]:Error Market Not Found ' || SQLERRM, 1, 125);
    scimf_common.write_log (v_code, --Log error into the LOGFILE
    'E',
    'p_mfcst_transform_master',
    v_errm,
    vr_market.marketid,
    'I'
    raise_application_error (-200001,
    'Market parameter not found for system'
    || pi_system
    po_error := TO_CHAR (SQLCODE) || ' -Error Message: ' || SQLERRM;
    po_status := -1;
    WHEN OTHERS
    THEN
    ROLLBACK;
    DBMS_OUTPUT.put_line ( '[E]:0-ERROR :-- '
    || ' --SQLCODE: '
    || SQLCODE
    || ' -Error Message: '
    || SQLERRM
    po_error := TO_CHAR (SQLCODE) || ' -Error Message: ' || SQLERRM;
    po_status := -1;
    END;

  • Help Tune a query

    Hi,
    Can you please help me tune a query?
    I have a dimension table PRODUCT which is having product data with millions of rows and another table (fact table) with more than millions of rows and it is called PRODUCT TRANSACTION.
    The PRODUCT TRANSACTION table has multiple rows for a given product with multiple issue dates. EX.
    PRODUCT ISSUE DATE
    A 10/28/2008
    B 11/02/2008
    C 05/28/2008
    D 06/27/2008
    E 07/28/2008
    I am doing JOIN between PRODUCT (dimension table) and fact (PRODUCT TRANSACTION TABLE) and just want a minimum of ISSUE DATE (means only one record from fact table for each product in dimension table).
    I have written query as
    SELECT PRODUCT_ID FROM
    PRODUCT_TRANSACTION AS PT
    INNER JOIN PRODUCT P ON
    P.PRODUCT_ID IN (SELECT PT.PRODUCT_ID FROM
    SELECT PT1.PRODUCT_ID, MIN (PT1.ISSUE_DATE) AS MINC
    FROM PRODUCT_TRANSACTION PT1
    GROUP BY PT1.PRODUCT_ID) B)
    This query takes forever. Is there a better way to accomplish this?
    Please suggest.

    Try this:
    SELECT
    PRODUCT_ID,
    min(issue_date)  keep(dense_rank first order by issue_date)
    FROM
    PRODUCT_TRANSACTION
    GROUP BY PRODUCT_IDRegards,
    Sayan M.

  • Pls. help tune this query

    This is the SQL i would like to tune for performace...
    The table structure is given below.
    The table has about 5 million rows.
    On the first day, load_flag has all the rows as 'I'.
    Then from the second day onwards only around 10% of records will be between Load_Start_Time and Load_End_Time. Among these around 40% will have Record_key like 'TP%'. And among those most of the records (95%)will have load_flag as 'U' and a very few (5%) as 'I'. At present there are unique and primary key indexes on record_key. Please advice me whether it's better to go for an index on any of these columns and what type would be better. I thought it would help to have a bit map index on load_flag and a function base index on SUBSTR (RECORD_KEY).
    Also pls. let me know if the order of predicates is right.
    Thanks in advance.
    M_STG_TPDB_TPD_TL_W_PH_LOI_CNTBLTY_STATUS_CE     SQ_STG_TPD_STG_TL_CS_EXTRACTED_RECS_MOD     "SELECT TPD_STG_TL_CS_EXTRACTED_RECS.RECORD_KEY, TPD_STG_TL_CS_EXTRACTED_RECS.DATA_SOURCE, TPD_STG_TL_CS_EXTRACTED_RECS.CONTACTABLE_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.LEGAL_OWNERSHIP_ISSUE_IND, TPD_STG_TL_CS_EXTRACTED_RECS.ADMIN_CONTROL_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.BANKRUPTCY_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.ASSIGNED_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.IN_TRUST_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.DIVORCE_CASE_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.POA_COP_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.SOURCE_EXTRACT_DATE_TIME
    FROM
    TPD_STG_TL_CS_EXTRACTED_RECS
    WHERE
    LOAD_FLAG IN ('I','U')
    AND SUBSTR (RECORD_KEY, 1,2)='TP'
    AND STG_UPDATE_DATE_TIME>'$$Load_Start_Time'
    AND STG_UPDATE_DATE_TIME<='$$Load_End_Time'"
    Table structure
    CREATE TABLE TPD_STG_TL_CS_EXTRACTED_RECS
    RECORD_KEY VARCHAR2(35 BYTE),
    SCHEME_NAME VARCHAR2(50 BYTE),
    ORGANISATION_NAME VARCHAR2(50 BYTE),
    SUPERIOR_TITLE_1 VARCHAR2(50 BYTE),
    TITLE_1 VARCHAR2(50 BYTE),
    FIRST_NAME_1 VARCHAR2(50 BYTE),
    MIDDLE_NAME_1 VARCHAR2(50 BYTE),
    SURNAME_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_1_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_2_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_3_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_4_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_5_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_6_1 VARCHAR2(50 BYTE),
    POST_CODE_1 VARCHAR2(12 BYTE),
    COUNTRY_1 VARCHAR2(50 BYTE),
    OVERSEAS_INDICATOR_1 CHAR(1 BYTE),
    DOB_1 NUMBER(8),
    GENDER_1 CHAR(1 BYTE),
    NINO_1 VARCHAR2(9 BYTE),
    DEATH_INDICATOR_1 CHAR(1 BYTE),
    PRODUCT_HOLDING_ROLE_TYPE_1 VARCHAR2(21 BYTE),
    GONE_AWAY_INDICATOR_1 CHAR(1 BYTE),
    THAMES_LEGAL_OWNERSHIP_IND_1 CHAR(1 BYTE),
    SOURCE_SYSTEM_PARTY_INDV_ID_1 VARCHAR2(15 BYTE),
    SUPERIOR_TITLE_2 VARCHAR2(50 BYTE),
    TITLE_2 VARCHAR2(50 BYTE),
    FIRST_NAME_2 VARCHAR2(50 BYTE),
    MIDDLE_NAME_2 VARCHAR2(50 BYTE),
    SURNAME_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_1_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_2_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_3_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_4_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_5_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_6_2 VARCHAR2(50 BYTE),
    POST_CODE_2 VARCHAR2(12 BYTE),
    COUNTRY_2 VARCHAR2(50 BYTE),
    OVERSEAS_INDICATOR_2 CHAR(1 BYTE),
    DOB_2 NUMBER(8),
    GENDER_2 CHAR(1 BYTE),
    NINO_2 VARCHAR2(9 BYTE),
    DEATH_INDICATOR_2 CHAR(1 BYTE),
    PRODUCT_HOLDING_ROLE_TYPE_2 VARCHAR2(21 BYTE),
    GONE_AWAY_INDICATOR_2 CHAR(1 BYTE),
    THAMES_LEGAL_OWNERSHIP_IND_2 CHAR(1 BYTE),
    SOURCE_SYSTEM_PARTY_INDV_ID_2 VARCHAR2(15 BYTE),
    JOINT_OWNER_INDICATOR CHAR(1 BYTE),
    JOINT_LIFE_TYPE NUMBER(1),
    SAME_ADDRESS_INDICATOR CHAR(1 BYTE),
    TITLE_LA1 VARCHAR2(50 BYTE),
    FIRST_NAME_LA1 VARCHAR2(50 BYTE),
    SURNAME_LA1 VARCHAR2(50 BYTE),
    DOB_LA1 NUMBER(8),
    TITLE_LA2 VARCHAR2(50 BYTE),
    FIRST_NAME_LA2 VARCHAR2(50 BYTE),
    SURNAME_LA2 VARCHAR2(50 BYTE),
    DOB_LA2 NUMBER(8),
    PRODUCT_HOLDING_REF_NUMBER VARCHAR2(28 BYTE),
    PARENT_PRODUCT_HOLDING_REF_NUM VARCHAR2(9 BYTE),
    OCDB_REFERENCE_NUMBER VARCHAR2(17 BYTE),
    BUSINESS_GROUP CHAR(3 BYTE),
    SCHEME_NUMBER VARCHAR2(8 BYTE),
    TRUSTEE_SEQUENCE_NUMBER NUMBER(10),
    MEMBER_NUMBER VARCHAR2(10 BYTE),
    PRSN_ID NUMBER(10),
    OLD_SCHEME_NUMBER VARCHAR2(8 BYTE),
    PUBLIC_SECTOR_INDICATOR CHAR(1 BYTE),
    ELIGIBLE_INDICATOR CHAR(1 BYTE),
    SCHEME_STATUS NUMBER(1),
    SCHEME_TYPE CHAR(2 BYTE),
    Q_DATE_WITH_PROFIT_STATUS NUMBER(1),
    A_DATE_WITH_PROFIT_STATUS NUMBER(1),
    LATEST_WITH_PROFIT_STATUS NUMBER(1),
    NPSW_INDICATOR CHAR(1 BYTE),
    PRODUCT_HOLDING_STATUS CHAR(1 BYTE),
    MATURITY_DATE_OF_CONTRACT NUMBER(8),
    DUE_END_DATE_OF_CONTRACT NUMBER(8),
    OUT_OF_FORCE_DATE NUMBER(8),
    OUT_OF_FORCE_REASON_CODE NUMBER(2),
    DATA_SOURCE VARCHAR2(3 BYTE),
    PRODUCT_TYPE VARCHAR2(30 BYTE),
    PRODUCT_DESCRIPTION VARCHAR2(50 BYTE),
    SERVICING_AGENT_NUMBER VARCHAR2(10 BYTE),
    CONTACTABLE_INDICATOR CHAR(1 BYTE),
    LEGAL_OWNERSHIP_ISSUE_IND CHAR(1 BYTE),
    ADMIN_CONTROL_INDICATOR CHAR(1 BYTE),
    BANKRUPTCY_INDICATOR CHAR(1 BYTE),
    ASSIGNED_INDICATOR CHAR(1 BYTE),
    IN_TRUST_INDICATOR CHAR(1 BYTE),
    DIVORCE_CASE_INDICATOR CHAR(1 BYTE),
    POA_COP_INDICATOR CHAR(1 BYTE),
    DONOR_POLICY_INDICATOR CHAR(1 BYTE),
    TAX_JURISDICTION NUMBER(2),
    INELIGIBLE_DATE NUMBER(8),
    INELIGIBILITY_REASON NUMBER(2),
    A_DATE_CASH_OR_BONUS_TYPE CHAR(1 BYTE),
    VALUATION_APPLICABLE_DATE NUMBER(8),
    A_DATE_PIP_AMOUNT NUMBER(12),
    A_DATE_NPSW_AMOUNT NUMBER(10),
    A_DATE_MINIMUM_APPLIED_AMOUNT NUMBER(10),
    A_DATE_MINIMUM_CALC_AMOUNT NUMBER(10),
    A_DATE_POLICY_VALUE NUMBER(16),
    A_DATE_DATE_PIP_CALCULATED NUMBER(8),
    A_DATE_ALGORITHM_NUMBER NUMBER(2),
    M_DATE_VOTING_VALUE NUMBER(12),
    M_DATE_POLICY_VALUE NUMBER(16),
    E_DATE_CASH_OR_BONUS_TYPE CHAR(1 BYTE),
    E_DATE_PIP_AMOUNT NUMBER(12),
    E_DATE_NPSW_AMOUNT NUMBER(10),
    E_DATE_MINIMUM_APPLIED_AMOUNT NUMBER(10),
    E_DATE_MINIMUM_CALC_AMOUNT NUMBER(10),
    E_DATE_POLICY_VALUE NUMBER(16),
    E_DATE_DATE_PIP_CALCULATED NUMBER(8),
    E_DATE_ALGORITHM_NUMBER NUMBER(2),
    P_DATE_CASH_OR_BONUS_TYPE CHAR(1 BYTE),
    P_DATE_PIP_AMOUNT NUMBER(12),
    P_DATE_NPSW_AMOUNT NUMBER(10),
    P_DATE_MINIMUM_APPLIED_AMOUNT NUMBER(10),
    P_DATE_MINIMUM_CALC_AMOUNT NUMBER(10),
    P_DATE_POLICY_VALUE NUMBER(16),
    P_DATE_DATE_PIP_CALCULATED NUMBER(8),
    P_DATE_ALGORITHM_NUMBER NUMBER(2),
    SOURCE_EXTRACT_DATE_TIME DATE,
    SCHEME_SEQUENCE_NUMBER NUMBER(3),
    LOAD_FLAG CHAR(1 BYTE),
    STG_CREATE_DATE_TIME DATE,
    STG_UPDATE_DATE_TIME DATE
    TABLESPACE TPDBS01A_DATA
    PCTUSED 0
    PCTFREE 10
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 128K
    NEXT 128K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    LOGGING
    NOCOMPRESS
    NOCACHE
    NOPARALLEL
    MONITORING;
    CREATE UNIQUE INDEX PK_STG_TL_CS_EXTRACTED_RECS ON TPD_STG_TL_CS_EXTRACTED_RECS
    (RECORD_KEY)
    LOGGING
    TABLESPACE TPDBS01A_DATA
    PCTFREE 10
    INITRANS 2
    MAXTRANS 255
    STORAGE (
    INITIAL 128K
    NEXT 128K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    NOPARALLEL;
    ALTER TABLE TPD_STG_TL_CS_EXTRACTED_RECS ADD (
    CONSTRAINT PK_STG_TL_CS_EXTRACTED_RECS
    PRIMARY KEY
    (RECORD_KEY)
    USING INDEX
    TABLESPACE TPDBS01A_DATA
    PCTFREE 10
    INITRANS 2
    MAXTRANS 255
    STORAGE (
    INITIAL 128K
    NEXT 128K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    ));

    I would like to discuss a bit more how a composite index is used. This is not anymore the question of the OP, but I think it will deepen my understanding and maybe that of others as well.
    So we have this situation to start with.
    * A select on two different columns.
    * An index on each column would lead to an INDEX RANGE SCAN because of the where condition.
    * Instead of 2 indexes where only one would be used (not considering bitmap conversions), we add a composite index on both columns.
    * The CBO will choose and access the index.
    Question is: How is this access is done in detail?
    So 400 rows come out of the index range scan.
    This would not be possible if it only scanned one of the two predicates. I agree. The output of the index seem to be only those (400) rows that fit with the where clause on both columns.
    This is supported by the fact that an Index only access is possible when we select only information that is in the index (Oracle 9i output).
    SQL> explain plan for
      2  select record_key
      3  from mytable
      4  where stg_update_date_time >= to_date('2007-11-11','yyyy-mm-dd')
      5  and stg_update_date_time < to_date('2007-11-12','yyyy-mm-dd')
      6  and record_key like 'TP%'
      7  /
    Explained.
    SQL>  select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    | Id  | Operation            |  Name       | Rows  | Bytes | Cost  |
    |   0 | SELECT STATEMENT     |             |   160 |  2400 |     2 |
    |   1 |  INDEX RANGE SCAN    | I1          |   160 |  2400 |     2 |
    Note: cpu costing is off, PLAN_TABLE' is old version
    9 rows selected.
    SQL> Unfortunately I don't see the filter operation, probably because the plan table is old in my system.
    The index is build on columns "stg_update_date_time" and "record_key". So it must access these columns in that order.
    I think, that maybe the range scan is done on the date column and then a further access/filter operation is done to rule out any index entries (leaf nodes) that do not fit with the LIKE 'TP%' expression.
    Since I expect that is is faster to access the data in the index than in the table this should improve performance quite a bit. It is not the same access plan/speed however as with a clause like this:
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    | Id  | Operation                   |  Name       | Rows  | Bytes | Cost  |
    |   0 | SELECT STATEMENT            |             |     1 |   520 |     3 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| MYTABLE     |     1 |   520 |     3 |
    |   2 |   INDEX RANGE SCAN          | I1          |     1 |       |     2 |
    Note: cpu costing is off, PLAN_TABLE' is old version
    10 rows selected.
    SQL> The difference can be seen in the cost estimation.
    I hope somebody does understand what I would like to point at.
    Result of this considerations:
    1) Composite index can be used
    2) The index is used as a range scan on one column and as a filter operation after this access on the second column. This is like an extra select statement inside the index structure.
    3) The resulting table access is as small as possible.
    4) A faster access plan can be achieved when the first column is accessed with direct (unique) scan on the first and a range scan on the second column.
    br Sven
    Message was edited by:
    Sven Weller

  • Need help in plsql cursor

    Hi All,
    I need to insert values into a table A of similar structure of other table B.(both havin same no of colums and same type).
    Im using a cursor to fetch the values from the table B and in loop im fetching the values from the cursor to the temporary variable of the same type as the table B and im trying to insert values into table A using the following statement
    insert into table A values(temp variable);
    when i tried executing the procedure it is showing an error "Not enough values".
    I not clear whether we can use the insert statement as above or is there any other way to achieve the same.
    Please help.
    Regards,
    Mohan

    You can use an INSERCT..SELECT instead of a PL/SQL procedure:
    Insert into TableA(col1, col2, col3)
    select column1, column2,column3
      from tableB;But if you do need (want) use PL/SQL write it this way:
    declare
    cursor cb is
    select select column1, column2,column3
      from tableB;
    begin
      for recB in cb loop
         Insert into TableA(col1, col2, col3)
            values (recB.column1,recB.column2,recB.column3);
      end loop;
    end;Max
    [My Italian Oracle blog|http://oracleitalia.wordpress.com/2010/01/10/crittografia-in-plsql-utilizzando-dbms_crypto/]

  • Simple query help in plsql - help

    oracle version : 10gR2
    indexes are created on each column, is there anyway to make them used while searching for the records rewriting the following query to test given data in any case (lower ,upper)...
    SELECT * FROM TX_USERS
    WHERE userid like decode( UPPER('Md'),null,userid, UPPER( 'MD')||'%' ) and
    first_name like decode(UPPER('Na'),null, first_name, UPPER( 'NA')||'%' ) AND
    LAST_name like decode(('Ra'),null, LAST_name, UPPER('RA')||'%' )
    -- list goes on..
    UPPER('Md') -- is the input values comes from form.. for example i_userid.. this query works fine .. is there anyway of getting indices used without using functional based indexing when we rewrite query like shown below??? input parameter valeus can be anything and table column values can be anything i.e. anycase (upper or lower or mix of both)..
    actual code would be
    upper(userid) like decode( UPPER(i_userid),null,userid, UPPER( i_userid)||'%' ) and
    upper(first_name) like decode(UPPER(i_first_name),null, first_name, UPPER( i_firstname)||'%' )
    if we put upper(userid) then index not used ..........anyway of rewriting using it or any other technique... or any other new way

    No, its not working... see the below..
    create table test5 as select owner, object_name, subobject_name, object_type from all_objects;
    create unique index test5_i5 on test5 (owner, object_name, subobject_name, object_type);
    select * from test5 where owner like 'SCOTT' AND OBJECT_NAME LIKE 'EMP';
    INDEX RANGE SCAN| TEST5_I5 | 4 | 248 | 1 (0)| 00:00:01 |
    but when i use
    select * from test5 where UPPER(OWNER) LIKE 'SCOTT%' AND UPPER(OBJECT_NAME) LIKE 'EMP%';
    TABLE ACCESS FULL| TEST5 | 3 | 186 | 65 (5)| 00:00:01 |
    i know it goes to full scan, i want to know is there any other way to make index used .. without using functional based indx...
    the reason is user can search any one of the column data and data is mixed case in table columns and/or conditions specified in query..
    .. any help...
    not sure how to use 'NLS_SORT=BINARY_CI' on multicolumn index and enable index used in search operation.. ANY OTHER WAY OF DOING THIS...
    requirements is
    mixed (lower,upper) data stored in db columns and mixed case data searched, 5 columns specified in where condition, data may be provided in search conditon to one or two or to all 5 columns in mixed case... matching records need to be returned.. suggest a good way of doing this... thnx

  • Need help in Plsql for Oracle Reports

    Hi i need urgent requirement for this, Kindly guide me. Since i couldnt do.
    Main Table:
    For example: Conside this table: (Card_no, month and year are unique constraint)
    Card_No Name Amount_1 Amount _2 Total Month Year
    1 Justin 50 1000 1050 Jan 2011
    1 Justin 100 500 600 Feb 2011
    2 Charles 50 100 150 Jan 2011
    1 Justin 100 50 150 Jan 2012
    1 Justin 50 1000 1050 Feb 2012
    1 Justin 100 500 600 Mar 2012
    2 Charles 50 100 150 Jan 2012
    1 Justin 100 50 150 Jan 2012
    Now i need Reports like this:
    1. When i select Year as 2012 and select amount1, i need report like this
    Card_No Name Jan Feb Mar Apr May June . . . . Dec Total
    1 Justin 100 50 100 0 0 0 . . . 0 250
    2 Charles 50 0 0 0 0 0 . . . 0 50
    2. If i select many years and select amount1, i need report like this
    Card_No Name Year Jan Feb Mar Apr May June . . . . Dec Total
    1 Justin 2012 100 50 100 0 0 0 . . . 0 250
    1 Justin 2011 50 100 0 0 0 0 0 150
    2 Charles 2012 50 0 0 0 0 0 . . . 0 50
    2 Charles 2011 50 0 0 0 0 0 . . . 0 50
    These are the two requirements
    Kindly guide me and many more suggestion also will be helpful
    Thanks in advance

    Actually you need to use matrix report in you report style to meet your requirement
    however please try below file if you use oracle 10g (I am not much sure as it was checked long time back)
    https://docs.google.com/file/d/0B6k7l8hLvpK2UnJwUDFRR1N5d2s/edit
    Best of luck
    Edited by: AppsLearner on Aug 3, 2012 12:49 AM

  • Please help regarding PLSQL coding standards

    Hi,
    Can you please send any document for PL/SQL coding standards,
    Please help.. I did nt find any good resources on net regarding..
    Pleease help me if any pdf regarding are exitst to my mail id
    [email protected]
    Thanks and Regards
    asp

    I did nt find any good resources on net regarding..Here is a list from the net for you to start with (courtesy of many of the fellow posters here in these forums), and there will be plenty more. Just need to search correctly.
    http://www.redhat.com/docs/manuals/waf/rhea-dg-waf-en-6.0/ap-sql-standards.html
    http://www.orafaq.com/faqplsql.htm
    http://www.williamrobertson.pwp.blueyonder.co.uk/documents/plsqlcodingstandards.html
    http://www.orafaq.com/node/48
    http://apex.oracle.com/pls/otn/f?p=2853:4:11598658413321972351::NO::P4_QA_ID:3262
    http://www.bbc.co.uk/guidelines/newmedia/technical/databases.shtml
    Message was edited by:
    Kamal Kishore
    Message was edited by:
    Kamal Kishore

  • Tune PLSQL block

    Table bk_logmnr_contents consists of the 150000 rows.
    And below block takes 90 minutes to execute the block.
    What changes i can do so that below block will tune?
    DECLARE
    CURSOR c_logmnr
    IS
    SELECT row_id,sql_redo
    FROM bk_logmnr_contents;
    text VARCHAR2(2000);
    BEGIN
         FOR i IN c_logmnr
         LOOP
              BEGIN
                   IF UPPER(i.SQL_REDO) LIKE 'INSERT INTO "TEST".%' THEN
                   IF UPPER(i.SQL_REDO) LIKE 'INSERT INTO "TEST"."LEAD"%' THEN
                             SELECT REPLACE(REPLACE( sql_redo, ',NULL);', ');' ),'"BOUNCE_MSG_T","")','"BOUNCE_MSG_T")')
                             INTO text
                             FROM bk_logmnr_contents
                             WHERE row_id =i.row_id
                             AND UPPER(SQL_REDO) LIKE 'INSERT INTO "TEST"."LEAD"%';
                             INSERT INTO bk_logmnr_contents_ins(sql_redo) VALUES(text);
                        ELSE
                             SELECT sql_redo
                             INTO text
                             FROM bk_logmnr_contents
                             WHERE row_id =i.row_id
                             AND UPPER(SQL_REDO) LIKE 'INSERT INTO "TEST".%';
                             INSERT INTO bk_logmnr_contents_ins(sql_redo) VALUES(text);
                        END IF;
                   END IF;
                   IF UPPER(i.SQL_REDO) LIKE 'DELETE FROM "TEST".%' THEN
                   IF UPPER(i.SQL_REDO) LIKE 'DELETE FROM "TEST"."FORMSVAL"%' THEN
                        SELECT REPLACE( SUBSTR(sql_redo,1,INSTR(sql_REDO,'ROWID')-6)||';', 'and "SYSCREATED" =', 'AND TO_DATE("SYSCREATED", ''DD-MON-RR'') =' ) sql_redo
                        INTO text
                        FROM bk_logmnr_contents
                        WHERE row_id =i.row_id
                        AND UPPER(i.SQL_REDO) LIKE 'DELETE FROM "TEST".%';
                        INSERT INTO bk_logmnr_contents_ins(sql_redo) VALUES(text);
                   ELSE     
                        SELECT SUBSTR(sql_redo,1,INSTR(sql_REDO,'ROWID')-6)||';' sql_redo
                        INTO text
                        FROM bk_logmnr_contents
                        WHERE row_id =i.row_id
                        AND UPPER(SQL_REDO) LIKE 'DELETE FROM "TEST".%';
                        INSERT INTO bk_logmnr_contents_ins(sql_redo) VALUES(text);
                        END IF;
                   END IF;
                   --DATABASE
                   IF UPPER(i.sql_REDO) LIKE 'UPDATE "TEST"."DATABASE"%' THEN
                        SELECT a.sql_redo|| b.ID||';'
                        INTO text
                        FROM DATABASE b,(SELECT SUBSTR(sql_redo,1,INSTR(sql_REDO,'ROWID')-1) || ' id =' sql_redo , row_id
                                       FROM bk_logmnr_contents WHERE row_id =i.row_id) a
                        WHERE UPPER(sql_REDO) LIKE 'UPDATE "TEST"."DATABASE"%'
                        AND a.row_id=b.ROWID AND b.ROWID = i.row_id;
                        INSERT INTO bk_logmnr_contents_ins(sql_redo) VALUES(text);
                   END IF;
                   --LEAD
                   IF UPPER(i.sql_REDO) LIKE 'UPDATE "TEST"."LEAD"%' THEN
                        SELECT a.sql_redo|| b.ID||';'
                        INTO text
                        FROM lead b,(SELECT SUBSTR(sql_redo,1,INSTR(sql_REDO,'ROWID')-1) || ' id =' sql_redo , row_id
                                       FROM bk_logmnr_contents WHERE row_id =i.row_id) a
                        WHERE UPPER(sql_REDO) LIKE 'UPDATE "TEST"."LEAD"%'
                        AND a.row_id=b.ROWID AND b.ROWID = i.row_id;
                        INSERT INTO bk_logmnr_contents_ins(sql_redo) VALUES(text);
                   END IF;
              EXCEPTION
                        WHEN OTHERS THEN
                        NULL;
              END;
         END LOOP;
    END;     
    Thanks,

    What you are doing is row by row (slow by slow) processing, because you are using a cursor loop with SQL embedded in it.
    This is generally bad practice.
    What you need to do is to minimise PL/SQL and maximise SQL. i.e. try and get rid of the loop and do as much processing in as few SQL statements as possible.
    An demonstration of the performance difference between doing a single SQL statement and the same functionality in a loop..
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_sysdate DATE;
      3  begin
      4    v_sysdate := SYSDATE;
      5    INSERT INTO mytable SELECT rownum FROM DUAL CONNECT BY ROWNUM <= 1000000;
      6    DBMS_OUTPUT.PUT_LINE('Single Transaction: Time Taken: '||ROUND(((SYSDATE-v_sysdate)*(24*60*60)),0));
      7    EXECUTE IMMEDIATE 'TRUNCATE TABLE mytable';
      8    v_sysdate := SYSDATE;
      9    FOR i IN 1..1000000
    10    LOOP
    11      INSERT INTO mytable (x) VALUES (i);
    12    END LOOP;
    13    DBMS_OUTPUT.PUT_LINE('Multi Transaction: Time Taken: '||ROUND(((SYSDATE-v_sysdate)*(24*60*60)),0));
    14    EXECUTE IMMEDIATE 'TRUNCATE TABLE mytable';
    15* end;
    SQL> /
    Single Transaction: Time Taken: 1
    Multi Transaction: Time Taken: 37
    PL/SQL procedure successfully completed.
    SQL>As you can see the single insert is vastly faster than the looped insert statements, both achieving the same results.

  • HELP NEEDED PLSQL urgent plz

    hi all,
    i would like to know if there is any other way to use LIKE statement in plsql.
    select count (distinct panel_nm) into lv_count
              from dcon_mv_raj
              where al_clinical_trial_nm=lv_trial_nm
              and panel_nm like '%lv_pan1%';
    when i am trying the above query ..it is giving me as the count '0' for the different lv_pan1 when i ran it in a procedue.but when i ran the same query in a sql editor it is working fine..
    need urgently please..
    thanks in advance
    phani

    Hallo,
    is lv_pan1 - variable ?
    Then you have to write the query dynamically
    or with INSTR- Function (IMHO, it's a better solution).
    select count (distinct panel_nm) into lv_count
    from dcon_mv_raj
    where al_clinical_trial_nm=lv_trial_nm
    and INSTR(panel_nm, lv_pan1) > 0;
    You search, whether variable panel_nm contains the values of lv_pan1
    Typos corrected.
    Regards
    Dmytro Dekhtyaryuk
    Message was edited by:
    dekhtyar

  • Need Help on Plsql!

    Hi,
    I am trying to Write a Pl/sql Script for Updating the object Count Status While dropping a user/Schema. i really don't know about the plsql Scripting, i am in learning stage i used below Script
    set serveroutput on;
    declare
    test26 varchar2(100);
    begin
    for test1 in (select count(*) out from dba_objects where owner='TEST08')
    loop
    if test1.out <= 0
    then
    dbms_output.put_line('done');
    elsif test1.out >= 0 then
    select count(*) out into test26 from dba_objects where owner='TEST08';
    dbms_output.put_line(test1.out);
    end if;
    end loop;
    end;
    i am getting the Result(Show Only the Current Count Status), but the Problem is , not Continuously updating the result. i need the result for every 15 seconds it should show the Count status of the Schema i.e 1456 after 15second 1359,1247,1001,997,551,201,55,......
    Please Advice....
    Thanks
    Shan

    You can use dbms_application_info.set_session_longops (from another session in your case as you are monitoring DDL operations which are visible to other sessions).
    Otherwise the long running processes should be "instrumented" to provide progress feedback using dbms_application_info.set_session_longops.
    DECLARE
            rindex    BINARY_INTEGER;
            slno      BINARY_INTEGER;
            totalwork number;
            sofar     number;
            obj       BINARY_INTEGER;
            st date;
            et date;
            chkfreq int := 3; ---- How frequently to poll in seconds
    BEGIN
    rindex := dbms_application_info.set_session_longops_nohint;
    sofar := 0;
    -- totalwork := 5; ---- determine total work that need to be done
    select count(*)
         into totalwork
         from dba_objects
         where owner='TEST08';
    WHILE sofar < totalwork LOOP
        st := sysdate;
        et := st + (1/(24*3600)) * chkfreq;
        while (st <= et) loop
            select sysdate into st from dual;
        end loop;
    --  sofar := sofar + 1;  ---- check how much work has been done
      select totalwork - count(*)
         into sofar
         from dba_objects
         where owner='TEST08';
      dbms_application_info.set_session_longops(rindex, slno,
        'Operation Somthing', obj, 0, sofar, totalwork, 'table', 'tables');
    END LOOP;
    END;
    /The progress can be monitored using yet another session, using v$session_longops.
    select * from v$session_longops where sid = <monitoring sessions SID>;vr,
    Sudhakar B.

  • Need help rewriting PLSQL as EVALUATE function

    Hello all,
    I've trying to convert some PLSQL (from Discoverer) into a column in Answers and I can't seem to get the formula correct.
    The original formula:
    MIN(Processed_Date) OVER(PARTITION BY Business_Area, Product, Serial_No)
    I assume this needs to be done in an EVALUATE function but I can't work out the correct syntax.
    This formula:
    EVALUATE('MIN(%1) OVER(PARTITION BY %2, %3, %4)', Processed_Date, Business_Area, Product, Serial_No)
    Generated this error:
    [nQSError: 10058] A general error has occurred. [nQSError: 22027] Union of non-compatible types. (HY000)
    I'm not sure what's causing the error and I've tried explicitly casting all the column, but still get errors.
    I'm open to any suggestions.
    Thanks.
    Edited by: jasonr on Dec 14, 2010 9:54 AM

    Jasonr,
    highlighted in bold is the change
    try this EVALUATE('MIN(%1) OVER(PARTITION BY %2, %3, %4)' AS DATE, Processed_Date, Business_Area, Product, Serial_No)
    do update if it resolved your issue.
    -bifacts
    http://www.obinotes.com
    J
    Edited by: bifacts on Dec 14, 2010 9:52 PM

Maybe you are looking for

  • Adding RAM to Macbook Pro 15 inch

    In reading about upgrade to Mtn Lion 10.8, there is recommendation for 4 GB of RAM.  I have 2GB in my Macbook Pro.  What is best approach to upgrade RAM? Must I go to Apple store or can this be done by someone with only mid-level technical skills? 

  • User exit in Equipment Address management

    Hi, I am looking for a user exit in 4.6C within Equipment maintenance but none of the enhancements that I have looked at seem to have the address information available. I have looked at Enhancements IEQM0001 to 3 and ITOB0001 - 6. We have a requireme

  • My time zone will not automatically reset

    I have been in South America for 2 months. Coming from the states, my time zone adjusted automatically (1 hour time difference). I spent a weekend in Uruguay and when I returned to Argentina, the time zone did not readjust to Argentina time, but stay

  • Will installing 10.5 erase everything on my computer ?

    Hello, this question may sound a bit ignorant but here goes...I have a Power Mac G5 running OS X 10.3.9, I came across a 10.5 install disc...I am concerned that if I install the new OS that I will lose all of my files...Such as Pro Tools, my Itunes m

  • "Could not create variable iterator" on creating ADF Parameter Form

    I've got a managed bean with a method; public String cmdLogin_action(String userName, String passWord) { // Add event code here... return "success"; I've created a data control, but whenever I try to drag it onto a page and select "Create ADF Paramet