Simple query takes time to run

Hi,
I have a simple query whcih takes about 20 mins to run.. here is the TKPROF forit:
  SELECT
    SY2.QBAC0,
    sum(decode(SALES_ORDER.SDCRCD,'USD', SALES_ORDER.SDAEXP,'CAD', SALES_ORDER.SDAEXP /1.0452))
  FROM
    JDE.F5542SY2  SY2,
    JDE.F42119  SALES_ORDER,
    JDE.F0116  SHIP_TO,
    JDE.F5542SY1  SY1,
   JDE.F4101  PRODUCT_INFO
WHERE
    ( SHIP_TO.ALAN8=SALES_ORDER.SDSHAN  )
    AND  ( SY1.QANRAC=SY2.QBNRAC and SY1.QAOTCD=SY2.QBOTCD  )
    AND  ( PRODUCT_INFO.IMITM=SALES_ORDER.SDITM  )
    AND  ( SY2.QBSHAN=SALES_ORDER.SDSHAN  )
    AND  ( SALES_ORDER.SDLNTY NOT IN ('H ','HC','I ')  )
    AND  ( PRODUCT_INFO.IMSRP1 Not In ('   ','000','689')  )
    AND  ( SALES_ORDER.SDDCTO IN  ('CO','CR','SA','SF','SG','SP','SM','SO','SL','SR')  )
    AND  (
    ( SY1.QACTR=SHIP_TO.ALCTR  )
    AND  ( PRODUCT_INFO.IMSRP1=SY1.QASRP1  )
  GROUP BY
  SY2.QBAC0
call     count       cpu    elapsed       disk      query    current        rows
Parse        1      0.07       0.07          0          0          0           0
Execute      1      0.00       0.00          0          0          0           0
Fetch       10     92.40     929.16     798689     838484          0         131
total       12     92.48     929.24     798689     838484          0         131
Misses in library cache during parse: 1
Optimizer goal: CHOOSE
Parsing user id: 62 
Rows     Row Source Operation
    131  SORT GROUP BY
3535506   HASH JOIN 
4026100    HASH JOIN 
    922     TABLE ACCESS FULL OBJ#(187309)
3454198     HASH JOIN 
  80065      INDEX FAST FULL SCAN OBJ#(30492) (object id 30492)
3489670      HASH JOIN 
  65192       INDEX FAST FULL SCAN OBJ#(30457) (object id 30457)
3489936       PARTITION RANGE ALL PARTITION: 1 9
3489936        TABLE ACCESS FULL OBJ#(30530) PARTITION: 1 9
  97152    TABLE ACCESS FULL OBJ#(187308)
OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
call     count       cpu    elapsed       disk      query    current        rows
Parse        1      0.07       0.07          0          0          0           0
Execute      2      0.00       0.00          0          0          0           0
Fetch       10     92.40     929.16     798689     838484          0         131
total       13     92.48     929.24     798689     838484          0         131
Misses in library cache during parse: 1kindly suggest how to resolve this...
OS is windows and its 9i DB...
Thanks

> ... you want to get rid of the IN statements.
They prevent Oracle from usering the index.
SQL> create table mytable (id,num,description)
  2  as
  3   select level
  4        , case level
  5          when 0 then 0
  6          when 1 then 1
  7          else 2
  8          end
  9        , 'description ' || to_char(level)
10     from dual
11  connect by level <= 10000
12  /
Table created.
SQL> create index i1 on mytable(num)
  2  /
Index created.
SQL> exec dbms_stats.gather_table_stats(user,'mytable')
PL/SQL procedure successfully completed.
SQL> set autotrace on explain
SQL> select id
  2       , num
  3       , description
  4    from mytable
  5   where num in (0,1)
  6  /
                                    ID                                    NUM DESCRIPTION
                                     1                                      1 description 1
1 row selected.
Execution Plan
Plan hash value: 2172953059
| Id  | Operation                    | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT             |         |  5001 |   112K|     2   (0)| 00:00:01 |
|   1 |  INLIST ITERATOR             |         |       |       |            |          |
|   2 |   TABLE ACCESS BY INDEX ROWID| MYTABLE |  5001 |   112K|     2   (0)| 00:00:01 |
|*  3 |    INDEX RANGE SCAN | I1      |  5001 |       |     1   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   3 - access("NUM"=0 OR "NUM"=1)Regards,
Rob.

Similar Messages

  • Why simple scrept takes time to run.....

    hello
    i write simple block as
    select consumer_number from receipts where consumer_number not in (select consumer_number from consumer_master);
    in that receipts,consumer_master r table and both having consumer_number field
    before some days i deleted same records from table receipts,consumer_master from that it takes time.
    i checked index on both table but its ok.
    plz help me.

    790948 wrote:
    RCI5142 @ msedcl> set autotrace TRACEONLY EXPLAIN
    RCI5142 @ msedcl> select consumer_number from receipts where consumer_number not in (select consumer_number from consumer_master);
    Execution Plan
    0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=2903788 Card=18126
    5 Bytes=2175180)
    1 0 FILTER
    2 1 TABLE ACCESS (FULL) OF 'RECEIPTS' (TABLE) (Cost=1153 Car
    d=181272 Bytes=2175264)
    3 1 INDEX (FAST FULL SCAN) OF 'PK_CON_NUMBER' (INDEX (UNIQUE
    )) (Cost=20 Card=1 Bytes=12)
    now what have to do this?You're doing a fast full scan on the index, which is probably better than a full table scan. CARD=1 means the subquery only expects to find one row - are your statistics current?
    Try variations on the query - different ways of coding it to get the same result set. The first thing I think of is a correlated NOT EXISTS subquery (untested)
    select consumer_number
      from receipts
    where not exists (
                 select 0
                  from consumer_master cm
                where cm.consumter_number = r.consumer_number
    );

  • How to get query execution time without running...?

    Hi ,
    I had one requirement .... as follows ......
    i had 3 sql statements . I need to execute only one sql which execution time is very less.
    Can any one help me , how to get query execution time without running that query and without using explain plan..?
    Thanks,
    Rajesh

    Kim Berg Hansen wrote:
    But you have ruled out explain plan for some reason, so I cannot help you.OP might get some answers if query was executed before - but since restart. Check V$SQL dynamic performance view for SQL_TEXT = your query. Then ROUND(ELAPSED_TIME / EXECUTIONS / 1000000) will give you average elapsed time.
    SY.
    Edited by: Solomon Yakobson on Apr 3, 2012 8:44 AM

  • Simple query takes 18 minutes to retrieve data....

    Hi,
    I am facing this problem at the customer site where a simple query on a table takes 18 minutes or more. Please find below the details.
    Table Structure
    CREATE TABLE dsp_data
    quantum_id NUMBER(11) NOT NULL,
    src      NUMBER(11) NOT NULL,
    call_status NUMBER(11) NOT NULL,
    dst NUMBER(11) NOT NULL,
    measurement_id NUMBER(11) NOT NULL,
    is_originating NUMBER(1)     NOT NULL,
    measurement_value NUMBER(15,4) NOT NULL,
    data_type_id NUMBER(3) NOT NULL,
    data VARCHAR2(200) NOT NULL
    TABLESPACE dsp_data_tspace
    STORAGE (PCTINCREASE 0 INITIAL 100K NEXT 1024K)
    PARTITION BY RANGE (quantum_id)
    (PARTITION dsp_data_default VALUES LESS THAN (100));
    CREATE INDEX dsp_data_idx ON dsp_data
    quantum_id,
    src,
         call_status,
    dst,
         measurement_id,
         is_originating,
    measurement_value,
    data_type_id
    TABLESPACE dsp_data_idx_tspace
    LOCAL;
    CREATE INDEX dsp_data_src_idx ON dsp_data
    src
    TABLESPACE dsp_data_idx_tspace
    LOCAL;
    CREATE INDEX dsp_data_dst_idx ON dsp_data
    dst
    TABLESPACE dsp_data_idx_tspace
    LOCAL;
    ALTER TABLE dsp_data
    ADD CONSTRAINT fk_dsp_data_1
    FOREIGN KEY
    quantum_id
    REFERENCES mds_measurement_intervals
    quantum_id
    ALTER TABLE dsp_data
    ADD CONSTRAINT fk_dsp_data_2
    FOREIGN KEY
    data_type_id
    REFERENCES mds_drilldown_types
    type_id
    ALTER TABLE dsp_data
    ADD CONSTRAINT pk_dsp_data
    PRIMARY KEY
    quantum_id,
    src,
    call_status,
    dst,
              measurement_id,
              is_originating,
    measurement_value,
    data_type_id,
    data
    USING INDEX
    TABLESPACE dsp_data_idx_tspace
    LOCAL;
    Table Space Creation
    All table space creation is done using following command
    CREATE TABLESPACE [tablespaceName]
    DATAFILE [tablespaceDatafile] SIZE 500M REUSE
    AUTOEXTEND ON NEXT 10240K
    DEFAULT STORAGE ( INITIAL 1024K
    NEXT 1024K
    MINEXTENTS 10
    MAXEXTENTS UNLIMITED
    PCTINCREASE 0
    Server Configuration on CUtsomer Site
    (1)     2 x Dual PA8900 Proc = 4GHz
    (2)     RAM = 16GB
    (3)     3 x Internal HDDs
    (4)     1 x External MSA-30 storage array (oracle db)
    Record Information On Customer Site
    select count(*) from dsp_data;
    COUNT(*)
    181931197
    select min (quantum_id) from dsp_data where dst=2;
    This takes 18 minutes or more....
    SQL> SQL> SQL> explain plan for select min (quantum_id) from dsp_data where dst=2;
    Explained.
    SQL> @?/rdbms/admin/utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 999040277
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Pstart| Pstop |
    | 0 | SELECT STATEMENT | | 1 | 14 | 1 (0)| 00:00:01 | | |
    | 1 | SORT AGGREGATE | | 1 | 14 | | | | |
    | 2 | FIRST ROW | | 92 | 1288 | 1 (0)| 00:00:01 | | |
    | 3 | PARTITION RANGE ALL | | 92 | 1288 | 1 (0)| 00:00:01 | 1 | 29 |
    |* 4 | INDEX FULL SCAN (MIN/MAX)| DSP_DATA_IDX | 92 | 1288 | 1 (0)| 00:00:01 | 1 | 29 |
    As mentioned above the query takes 18 minutes or more. This is a critical issue at customer. Can you please give your suggestions how to improve and reduce the query time. Thanks in advance.

    Hi,
    I did the following changes in the indexes of table.
    drop index DSP_DATA_IDX;
    create index DSP_DATA_MEASUREMENT_ID_IDX on DSP_DATA (MEASUREMENT_ID) TABLESPACE dsp_data_idx_tspace LOCAL;
    After that I did explain plan,
    explain plan for select min(QUANTUM_ID) from mds.DSP_DATA where SRC=11;
    PLAN_TABLE_OUTPUT
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU
    | 0 | SELECT STATEMENT | | 1 | 11 | 3 (0
    | 1 | SORT AGGREGATE | | 1 | 11 |
    | 2 | FIRST ROW | | 430K| 4626K| 3 (0
    | 3 | PARTITION RANGE ALL | | 430K| 4626K| 3 (0
    | 4 | INDEX FULL SCAN (MIN/MAX)| PK_DSP_DATA | 430K| 4626K| 3 (0
    Note
    - 'PLAN_TABLE' is old version
    14 rows selected
    SELECT table_name, index_name, monitoring, used FROM v$object_usage;
    TABLE_NAME INDEX_NAME MONITORING USED
    DSP_DATA DSP_DATA_SRC_IDX YES NO
    It seems that DSP_DATA_SRC_IDX is not getting used in query. What changes do i need to make so that DSP_DATA_SRC_IDX index gets used.
    Also, you have stated that to create global index on src and dst. How do i create them.
    Thanks in Advance.
    Edited by: 780707 on Jul 8, 2010 11:58 PM

  • Query takes time to execute

    I am creating a jsp application . . . .I am retreiving some values from my database oracle 10g..my query taking time to execute even in isql plus..am uisng tomcat5 and oracle 10gR2..can anyone pls tell me why it happens...my query fetches data from four tables...i dont know exactly why its taking so muc time say 50seconds...when i run the application in my local host it retrievs fast when i do that in server it creates a problem..
    Actually it works fine when i deployed in my client server it takes time sometimes it takes atmost one minute
    1.pls tell me how can i test my query about the performance
    2.is der any command in oracle to test
    3.how much bytes it takes

    Look at this thread...
    When your query takes too long ...

  • This simple query takes 2 hrs. How to improve it??

    This is a simple query. It takes 2 hours to run this query. Tables have over 100,000 rows.
    SELECT
      TO_CHAR(BC_T_ARRIVALS.ARR_FLIGHT_DATE,'DD/MM/YYYY') ARR_FLIGHT_DATE
    FROM
      BC_T_ARRIVALS a,  BC_M_FLIGHTS f
    WHERE
      a.ARR_FLT_SEQ_NO = f.FLT_SEQ_NO AND
      f.FLT_LOC_CODE       = PK_BC_R_LOCATIONS.FN_SEL_LOC_CODE('BANDARANAYAKE INTERNATIONAL AIRPORT')  AND TO_CHAR(a.ARR_FLIGHT_DATE,'YYYY/MM/DD') >= TO_CHAR(:P_FROM_DATE,'YYYY/MM/DD')
    AND TO_CHAR(a.ARR_FLIGHT_DATE,'YYYY/MM/DD') <= TO_CHAR(:P_TO_DATE,'YYYY/MM/DD')
    UNION
    SELECT
      TO_CHAR(BC_T_DEPARTURES.DEP_FLIGHT_DATE,'DD/MM/YYYY') DEP_FLIGHT_DATE
    FROM
      BC_T_DEPARTURES d, BC_M_FLIGHTS f
    WHERE
      d.DEP_FLT_SEQ_NO = BC_M_FLIGHTS.FLT_SEQ_NO  AND
      f.FLT_LOC_CODE = PK_BC_R_LOCATIONS.FN_SEL_LOC_CODE('BANDARANAYAKE INTERNATIONAL AIRPORT')  AND TO_CHAR(d.DEP_FLIGHT_DATE,'YYYY/MM/DD') >= TO_CHAR(:P_FROM_DATE,'YYYY/MM/DD')
    AND TO_CHAR(d.DEP_FLIGHT_DATE,'YYYY/MM/DD') <= TO_CHAR(:P_TO_DATE,'YYYY/MM/DD')As I see it, this query will not make the DB engine use any indexes since expressions are used in the 'WHERE' clause. Am I correct?
    How can we improve the performance of this query???

    Maybe (do you really need to convert dates to chars ? That might prevent index use ...)
    select f.BC_M_FLIGHTS,
           TO_CHAR(BC_T_DEPARTURES.DEP_FLIGHT_DATE,'DD/MM/YYYY') DEP_FLIGHT_DATE,
           TO_CHAR(BC_T_ARRIVALS.ARR_FLIGHT_DATE,'DD/MM/YYYY') ARR_FLIGHT_DATE
      from (select BC_M_FLIGHTS,
                   FLT_LOC_CODE
              from BC_M_FLIGHTS
             where FLT_LOC_CODE = PK_BC_R_LOCATIONS.FN_SEL_LOC_CODE('BANDARANAYAKE INTERNATIONAL AIRPORT')
           ) f,
           BC_T_ARRIVALS a,
           BC_T_DEPARTURES d
    where f.BC_M_FLIGHTS = a.ARR_FLT_SEQ_NO
       and f.BC_M_FLIGHTS = d.DEP_FLT_SEQ_NO
       and (TO_CHAR(a.ARR_FLIGHT_DATE,'YYYY/MM/DD') between TO_CHAR(:P_FROM_DATE,'YYYY/MM/DD') and TO_CHAR(:P_TO_DATE,'YYYY/MM/DD')
        or  TO_CHAR(d.DEP_FLIGHT_DATE,'YYYY/MM/DD') between TO_CHAR(:P_FROM_DATE,'YYYY/MM/DD') and TO_CHAR(:P_TO_DATE,'YYYY/MM/DD')
           )Regards
    Etbin
    Edited by: Etbin on 2.3.2012 18:44
    select column list altered

  • Query takes time to execute. Review this query and give me a possible quere

    SELECT DISTINCT A.REFERENCE_NUMBER
    FROM A,B,C
    WHERE DF_N_GET_CONTRACT_STATUS (A.REFERENCE_NUMBER, TRUNC (SYSDATE)) = 1
    AND ( B.CHQ_RTN_INDICATOR IS NULL AND B.CHALLAN_NUMBER IS NULL
    AND C.INSTRUMENT_TYPE IN (1, 2) AND C.MODULE_CODE = 5 )
    AND ( A.HEADER_KEY = B.HEADER_KEY AND C.HEADER_KEY = B.HEADER_KEY);
    This query takes 3 minutes to execute. I want to improve the performance so that it can execute with in seconds.
    Table A has 10 lakhs record.
    Table B has 3.7 lakhs record.
    Table C has 5.3 lakhs record. Consider DF_N_GET_CONTRACT_STATUS as function. REFERENCE_NUMBER is the type of Varchar2(20).
    Plz give me a correct logical and fastest execution query for the same.
    Thanks in advance.

    I would agree with the post from Santosh above that you should review the guidelines for posting a tuning request. This is VERY important. It is impossile to come up with any useful suggestions without the proper information.
    In the case of your query, I would probably focus my attention on the function that you have defined. What happens if the condition using the DF_N_GET_CONTRACT_STATUS function is removed? Does it still take 3 minutes?
    SELECT reference_number
    from (
      SELECT DISTINCT A.REFERENCE_NUMBER
      FROM A,B,C
      WHERE ( B.CHQ_RTN_INDICATOR IS NULL AND B.CHALLAN_NUMBER IS NULL
      AND C.INSTRUMENT_TYPE IN (1, 2) AND C.MODULE_CODE = 5 )
      AND ( A.HEADER_KEY = B.HEADER_KEY AND C.HEADER_KEY = B.HEADER_KEY)
    where DF_N_GET_CONTRACT_STATUS(reference_number, trunc(sysdate)) = 1;Of course, the query above really depends on the cardinality of the returned data..... which is impossible to know without following the posting guidelines. This query could return anywhere between 0 rows and 2x10^17 rows. And in the latter case evaluating the function at the end wouldn't make any difference.
    Also, do you really need the distinct? Does it make any difference? Most of the time that I see distinct, to me it either means the query is wrong or the data model is wrong.

  • Query takes time

    Hi All
    one of my query is taking too much time and really appreciate that if you people guide me how to get it fast. I'm using Oracle 11g Enterprise Release 11.2.0.2.0 64 bit version. My query is below and this query extract around 1 million records.
    Query
    Select distinct group_number grp_nbr, ltrim(group_number,'0') trimed_grp_nbr,section_code sct, enrolment_groups.group_id,
    enrolment_groups.segment_code,market_sgmt_attr_ascns.role_type_code,market_sgmt_attr_ascns.part_attr_type_code,
    nvl((select 'Y' from info where ltrim(info.grp_nbr,'0')=group_number
    and ltrim(rtrim(info.sct))=section_code
    and subscriber_id_type='S'),'N') Mandatory_flag,
    min(to_date(coverage_period.enr.group_eff_date)) over (partition by enrolment_groups.group_id) Min_Effective_date,
    nvl((select 'Y' from info where ltrim(info.grp_nbr,'0')=group_number
    and ltrim(rtrim(info.sct))=section_code
    and subscriber_id_type='S' and id_code='1'),'N') identification_flag
    from coverage_period,
    enrolment_groups,
    market_sgmt_attr_ascns
    Where ltrim(coverage_period.grp_nbr,'0')=enrolment_groups.group_number
    and ltrim(rtrim(coverage_period.sct))=enrolment_groups.section_code
    and enrolment_groups.segment_code=market_sgmt_attr_ascns.segment_code
    and market_sgmt_attr_ascns='GRP'
    and market_sgmt_attr_ascns.part_attr_type_code='ABR-PART'
    and group_number||'/'section_code in
    Select ltrim(info.grp_nbr,'0')||'/'||ltrim(rtrim(info.sct)) g_s
    from info
    where 1=1
    and info.subscriber_id_type='S')
    I have to get million of records and this query will take too much time. I really appreciate if you could help me out. Thanks
    Regards
    Shumail

    I'm working as an ETL Developer and I created a package in SQL Developer and my select query returned around 1 million rows and then these rows inserted into one of my table by using insert into table statement.
    I don't understand what do you mean by this statement
    it must do a SORT to get the distinct rows.
    I did one mistake, my whole package insert around 1 million records and if I'm talking about this specific query then it return only 88 rows and it will take like 5 minutes and I use the same select logic means IN clause and other clauses through out my my package by using Union but my package will take too much time. My concern is that is there any way to change this query logic to get result faster.
    For example
    I use in clause to compare group_number and section_code as well as some other stuff like I use 'Select 'Y' .........' in some places. Please help me out that is there any other way to query these statement to get result faster. Thanks
    Edited by: 976593 on Apr 10, 2013 7:17 PM
    Edited by: 976593 on Apr 10, 2013 7:22 PM

  • Query takes longer to run with indexes.

    Here is my situation. I had a query which I use to run in Production (oracle 9.2.0.5) and Reporting database (9.2.0.3). The time taken to run in both databases was almost the same until 2 months ago which was about 2 minutes. Now in production the query does not run at all where as in Reporting it continues to run in about 2 minutes. Some of the things I obsevred in P are 1) the optimizer_index_cost_adj parameter was changed to 20 from 100 in order to improve the performance of a paycalc program about 3 months ago. Even with this parameter being set to 20, the query use to run in 2 minutes until 2 months ago. in the last two months the GL table increased in size from 25 million rows to 27 million rows. With optimizer_index_cost_adj of 20 and Gl table of 25 million rows it runs fine, but with 27 million rows it does not run at all. If I change the value of optimizer_index_cost_adj to 100 then the query runs with 27 million rows in 2 minutes and I found that it uses full table scan. In Reporting database it always used full table sacn as found thru explain plan. CBO determines which scan is best and it uses that. So my question is that by making optimizer_index_cost_adj = 20, does oracle forces it to use index scan when the table size is 27 million rows? Isn't the index scan is not faster than full table scan? In what situation the full table scan is faster than index scan? If I drop all the indexes on the GL table then the query runs faster in production as it uses full table scan. What is the real benefit of changing optimizer_index_cost_adj values? Any input is most welcome.

    Isn't the index scan is not faster than full table scan? In what situation the full table scan is faster than index scan? No. It is not about which one is the "+fastest+" as that concept is flawed. How can an index be "faster" than a table for example? Does it have better tires and shinier paint job? ;-)
    It is about the amount of I/O that the database needs to perform in order to use that object's contents for resolving/executing that applicable SQL statement.
    If the CBO determines that it needs a 100 widgets worth of I/O to scan the index, and then another 100 widgets of I/O to scan the table, it may decide to not use the index at all, as a full table scan will cost only a 180 I/O widgets - 20 less than the combined scanning of index and table.
    Also, a full scan can make use of multi-block reads - and this, on most storage/file systems, is faster than single block reads.
    So no - a full table scan is NOT a Bad Thing (tm) and not an indicator of a problem. The thing that is of concern is the amount of I/O. The more I/O, the slower the operation. So obviously, we want to make sure that we design SQL that requires the minimal amount of I/O, design a database that support minimal I/O to find the required data (using clusters/partitions/IOTs/indexes/etc), and then check that the CBO also follows suit (which can be the complex bit).
    But before questioning the CBO, first question your code and design - and whether or not they provide the optimal (smallest) I/O footprint for the job at hand.

  • Query Performance - Query very slow to run

    I have built a query to show payroll costings per month per employee by cost centres for the current fiscal year. The cost centres are selected with a hierarchy variable - it's quite a latrge hierarchy. The problem is the query takes ages to run - nearly ten minutes. It's built on a DSO so I cant aggregate it. Is there anything I can do to improve performance.

    Hi Joel,
    Walkthrough Checklist for Query Performance:
    1. If exclusions exist, make sure they exist in the global filter area. Try to remove exclusions by subtracting out inclusions.
    2. Use Constant Selection to ignore filters in order to move more filters to the global filter area. (Use ABAPer to test and validate that this ensures better code)
    3. Within structures, make sure the filter order exists with the highest level filter first.
    4. Check code for all exit variables used in a report.
    5. Move Time restrictions to a global filter whenever possible.
    6. Within structures, use user exit variables to calculate things like QTD, YTD. This should generate better code than using overlapping restrictions to achieve the same thing. (Use ABAPer to test and validate that this ensures better code).
    7. When queries are written on multiproviders, restrict to InfoProvider in global filter whenever possible. MultiProvider (MultiCube) queries require additional database table joins to read data compared to those queries against standard InfoCubes (InfoProviders), and you should therefore hardcode the infoprovider in the global filter whenever possible to eliminate this problem.
    8. Move all global calculated and restricted key figures to local as to analyze any filters that can be removed and moved to the global definition in a query. Then you can change the calculated key figure and go back to utilizing the global calculated key figure if desired
    9. If Alternative UOM solution is used, turn off query cache.
    10. Set read mode of query based on static or dynamic. Reading data during navigation minimizes the impact on the R/3 database and application server resources because only data that the user requires will be retrieved. For queries involving large hierarchies with many nodes, it would be wise to select Read data during navigation and when expanding the hierarchy option to avoid reading data for the hierarchy nodes that are not expanded. Reserve the Read all data mode for special queriesu2014for instance, when a majority of the users need a given query to slice and dice against all dimensions, or when the data is needed for data mining. This mode places heavy demand on database and memory resources and might impact other SAP BW processes and tasks.
    11. Turn off formatting and results rows to minimize Frontend time whenever possible.
    12. Check for nested hierarchies. Always a bad idea.
    13. If "Display as hierarchy" is being used, look for other options to remove it to increase performance.
    14. Use Constant Selection instead of SUMCT and SUMGT within formulas.
    15. Do review of order of restrictions in formulas. Do as many restrictions as you can before calculations. Try to avoid calculations before restrictions.
    16. Check Sequential vs Parallel read on Multiproviders.
    17. Turn off warning messages on queries.
    18. Check to see if performance improves by removing text display (Use ABAPer to test and validate that this ensures better code).
    19. Check to see where currency conversions are happening if they are used.
    20. Check aggregation and exception aggregation on calculated key figures. Before aggregation is generally slower and should not be used unless explicitly needed.
    21. Avoid Cell Editor use if at all possible.
    22. Make sure queries are regenerated in production using RSRT after changes to statistics, consistency changes, or aggregates.
    23. Within the free characteristics, filter on the least granular objects first and make sure those come first in the order.
    24. Leverage characteristics or navigational attributes rather than hierarchies. Using a hierarchy requires reading temporary hierarchy tables and creates additional overhead compared to characteristics and navigational attributes. Therefore, characteristics or navigational attributes result in significantly better query performance than hierarchies, especially as the size of the hierarchy (e.g., the number of nodes and levels) and the complexity of the selection criteria increase.
    25. If hierarchies are used, minimize the number of nodes to include in the query results. Including all nodes in the query results (even the ones that are not needed or blank) slows down the query processing. The u201Cnot assignedu201D nodes in the hierarchy should be filtered out, and you should use a variable to reduce the number of hierarchy nodes selected.
    Regards
    Vivek Tripathi

  • Simple query taking so long time to run

    Below are the queries which are taking very long time to run. It pulls 4 million records approx on first query.
    How can it run fast?
    Thank you.
    SELECTPerson_DEID[CP1] ,
    Admit_DT,
    Discharge_DT, DRG_CD,
    cast (LineAllowedAmount
    AS money)
    as FacAA
    into
    FOET
    FROMdbo.mh_fac_claims_final[CP2] 
    group
    by Person_DEID,
    Admit_DT,
    Discharge_DT, DRG_CD,
    LineAllowedAmount;
    go
    select
    Person_DEID,
    Admit_DT, Discharge_DT,
    DRG_CD, sum(facAA)
    as FacAA_SUM[CP3] 
    from
    dbo.FOET
    group
    by Person_DEID,
    Admit_DT,
    Discharge_DT, DRG_CD,
    facAA;

    Below are the queries which are taking very long time to run. It pulls 4 million records approx on first query.
    How can it run fast?
    Thank you.
    SELECTPerson_DEID[CP1] ,
    Admit_DT,
    Discharge_DT, DRG_CD,
    cast (LineAllowedAmount
    AS money)
    as FacAA
    into
    FOET
    FROMdbo.mh_fac_claims_final[CP2] 
    group
    by Person_DEID,
    Admit_DT,
    Discharge_DT, DRG_CD,
    LineAllowedAmount;
    go
    select
    Person_DEID,
    Admit_DT, Discharge_DT,
    DRG_CD, sum(facAA)
    as FacAA_SUM[CP3] 
    from
    dbo.FOET
    group
    by Person_DEID,
    Admit_DT,
    Discharge_DT, DRG_CD,
    facAA;
    select    Person_DEID,Admit_DT,Discharge_DT,DRG_CD, convert(money,sum(LineAllowedAmount)) as FacAA_SUM[CP3] 
    into FOET
    FROM dbo.mh_fac_claims_final[CP2] 
    group by Person_DEID, Admit_DT, Discharge_DT, DRG_CD
    There is no grouping, u are calculating 4m records in second query. Maybe try above instead (already suggested)? Can u check how long above query takes to run?

  • Simple Select query with 'where', 'and', 'between' clauses takes time

    Hi,
    I have a select query as below
    SELECT * FROM (SELECT a.*,ROWNUM currentStartRecord From (select ai_inbound.ai_inb_seq tableseq,'AI_INBOUND' tablename,'INBOUND' direction,ai_inbound.appl,ai_inbound.ai_date datetime,ai_inbound.ic_receiver_id pg_id,ai_inbound.ic_sender_id tp_id,ai_inbound.session_no,ai_inbound.ic_ctl_no,ai_inbound.msg_set_id msg_type,ai_inbound.appl_msg_ctl_no reference_no,ai_inbound.fg_version version,ai_inbound.msg_status status,ai_inbound.input_file_name,ai_inbound.output_file_name,ai_inbound.ack_file_name from ai_inbound where ai_inbound.appl = ? and ai_inbound.ai_date between ? and ? )a where ROWNUM <= 49)where currentStartRecord >= 0
    The above query takes longer time through application than expected when the date fields are passed whereas it works fine when no date fields are passed. We are using oracle9.2 version of the database. All the indexed columns and partitioned indexed columns are rebuild.
    Kindly let me know how can i tune up the query to improve the performance.
    Thanks

    Hi,
    I have a select query as below
    SELECT * FROM (SELECT a.*,ROWNUM currentStartRecord From (select ai_inbound.ai_inb_seq tableseq,'AI_INBOUND' tablename,'INBOUND' direction,ai_inbound.appl,ai_inbound.ai_date datetime,ai_inbound.ic_receiver_id pg_id,ai_inbound.ic_sender_id tp_id,ai_inbound.session_no,ai_inbound.ic_ctl_no,ai_inbound.msg_set_id msg_type,ai_inbound.appl_msg_ctl_no reference_no,ai_inbound.fg_version version,ai_inbound.msg_status status,ai_inbound.input_file_name,ai_inbound.output_file_name,ai_inbound.ack_file_name from ai_inbound where ai_inbound.appl = ? and ai_inbound.ai_date between ? and ? )a where ROWNUM <= 49)where currentStartRecord >= 0
    The above query takes longer time through application than expected when the date fields are passed whereas it works fine when no date fields are passed. We are using oracle9.2 version of the database. All the indexed columns and partitioned indexed columns are rebuild.
    Kindly let me know how can i tune up the query to improve the performance.
    Thanks

  • Why the 'LIKE' operator takes so much time to run?

    I have a table T with 3 columns and 3 indexes:
    CREATE TABLE T
    id VARCHAR2(38) NOT NULL,
    fid VARCHAR2(38) NOT NULL,
    val NVARCHAR2(2000) NOT NULL
    ALTER TABLE T ADD (CONSTRAINT pk_t PRIMARY KEY (id,fid));
    CREATE INDEX t_fid ON T(fid);
    CREATE INDEX t_val ON T(val);
    Then I have the following two queries which differ in only one place - the 1st one uses the '=' operator whereas the 2nd uses 'LIKE'. Both queries have the identical execution plan and return one identical row. However, the 1st query takes almost 0 second to execute, and the 2nd one takes more than 12 seconds, on a pretty beefy machine. I had played with the target text, like placing '%' here and/or there, and observed the similar timing every time.
    So I am wondering what I should change to make the 'LIKE' operator run as fast as the '=' operator. I know CONTEXT/CATALOG index is a viable approach, but I am just trying to find out if there is a simpler alternative, such as a better use of the index t_val.
    1) Query with '=' operator
    SELECT id
    FROM T
    WHERE fid = '{999AE6E4-1ED9-459B-9BB0-45C913668C8C}'
    AND val = '3504038055275883124';
    2) Query with 'LIKE' operator
    SELECT id
    FROM T
    WHERE fid = '{999AE6E4-1ED9-459B-9BB0-45C913668C8C}'
    AND val LIKE '3504038055275883124';
    Execution Plan
    0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=1 Card=1 Bytes=99)
    1 0 TABLE ACCESS (BY INDEX ROWID) OF 'T' (Cost=1 Card=1 Bytes=99)
    2 1 INDEX (RANGE SCAN) OF 'T_VAL' (NON-UNIQUE) (Cost=4 Card=12)

    I will for sure try to change the order of the PK and see whether there will be any impact to the performance.
    In our application, val is much closer to a unique value than fid. In the example query, the execution plan showed that the index on val was indeed used in the execution of the query. That's why the 1st query took almost no time to return (our table T has more than 6 million rows).
    I was hoping the 'LIKE' operator would utilize the t_val index effectively and provide similar performance to the '=' operator. But apparently that's not the case, or needs some tricks.

  • SELECT query takes too much time! Y?

    Plz find my SELECT query below:
    select w~mandt
    wvbeln wposnr wmeins wmatnr wwerks wnetwr
    wkwmeng wvrkme wmatwa wcharg w~pstyv
    wposar wprodh wgrkor wantlf wkztlf wlprio
    wvstel wroute wumvkz wumvkn wabgru wuntto
    wawahr werdat werzet wfixmg wprctr wvpmat
    wvpwrk wmvgr1 wmvgr2 wmvgr3 wmvgr4 wmvgr5
    wbedae wcuobj w~mtvfp
    xetenr xwmeng xbmeng xettyp xwepos xabart
    x~edatu
    xtddat xmbdat xlddat xwadat xabruf xetart
    x~ezeit
    into table t_vbap
    from vbap as w
    inner join vbep as x on xvbeln = wvbeln and
    xposnr = wposnr and
    xmandt = wmandt
    where
    ( ( werdat > pre_dat ) and ( werdat <= w_date ) ) and
    ( ( ( erdat > pre_dat and erdat < p_syndt ) or
    ( erdat = p_syndt and erzet <= p_syntm ) ) ) and
    w~matnr in s_matnr and
    w~pstyv in s_itmcat and
    w~lfrel in s_lfrel and
    w~abgru = ' ' and
    w~kwmeng > 0 and
    w~mtvfp in w_mtvfp and
    x~ettyp in w_ettyp and
    x~bdart in s_req_tp and
    x~plart in s_pln_tp and
    x~etart in s_etart and
    x~abart in s_abart and
    ( ( xlifsp in s_lifsp ) or ( xlifsp = ' ' ) ).
    The problem: It takes too much time while executing this statement.
    Could anybody change this statement and help me out to reduce the DB Access time?
    Thx

    Ways of Performance Tuning
    1.     Selection Criteria
    2.     Select Statements
    •     Select Queries
    •     SQL Interface
    •     Aggregate Functions
    •     For all Entries
    Select Over more than one internal table
    Selection Criteria
    1.     Restrict the data to the selection criteria itself, rather than filtering it out using the ABAP code using CHECK statement. 
    2.     Select with selection list.
    SELECT * FROM SBOOK INTO SBOOK_WA.
      CHECK: SBOOK_WA-CARRID = 'LH' AND
             SBOOK_WA-CONNID = '0400'.
    ENDSELECT.
    The above code can be much more optimized by the code written below which avoids CHECK, selects with selection list
    SELECT  CARRID CONNID FLDATE BOOKID FROM SBOOK INTO TABLE T_SBOOK
      WHERE SBOOK_WA-CARRID = 'LH' AND
                  SBOOK_WA-CONNID = '0400'.
    Select Statements   Select Queries
    1.     Avoid nested selects
    SELECT * FROM EKKO INTO EKKO_WA.
      SELECT * FROM EKAN INTO EKAN_WA
          WHERE EBELN = EKKO_WA-EBELN.
      ENDSELECT.
    ENDSELECT.
    The above code can be much more optimized by the code written below.
    SELECT PF1 PF2 FF3 FF4 INTO TABLE ITAB
        FROM EKKO AS P INNER JOIN EKAN AS F
          ON PEBELN = FEBELN.
    Note: A simple SELECT loop is a single database access whose result is passed to the ABAP program line by line. Nested SELECT loops mean that the number of accesses in the inner loop is multiplied by the number of accesses in the outer loop. One should therefore use nested SELECT loops only if the selection in the outer loop contains very few lines or the outer loop is a SELECT SINGLE statement.
    2.     Select all the records in a single shot using into table clause of select statement rather than to use Append statements.
    SELECT * FROM SBOOK INTO SBOOK_WA.
      CHECK: SBOOK_WA-CARRID = 'LH' AND
             SBOOK_WA-CONNID = '0400'.
    ENDSELECT.
    The above code can be much more optimized by the code written below which avoids CHECK, selects with selection list and puts the data in one shot using into table
    SELECT  CARRID CONNID FLDATE BOOKID FROM SBOOK INTO TABLE T_SBOOK
      WHERE SBOOK_WA-CARRID = 'LH' AND
                  SBOOK_WA-CONNID = '0400'.
    3.     When a base table has multiple indices, the where clause should be in the order of the index, either a primary or a secondary index.
    To choose an index, the optimizer checks the field names specified in the where clause and then uses an index that has the same order of the fields. In certain scenarios, it is advisable to check whether a new index can speed up the performance of a program. This will come handy in programs that access data from the finance tables.
    4.     For testing existence, use Select.. Up to 1 rows statement instead of a Select-Endselect-loop with an Exit. 
    SELECT * FROM SBOOK INTO SBOOK_WA
      UP TO 1 ROWS
      WHERE CARRID = 'LH'.
    ENDSELECT.
    The above code is more optimized as compared to the code mentioned below for testing existence of a record.
    SELECT * FROM SBOOK INTO SBOOK_WA
        WHERE CARRID = 'LH'.
      EXIT.
    ENDSELECT.
    5.     Use Select Single if all primary key fields are supplied in the Where condition .
    If all primary key fields are supplied in the Where conditions you can even use Select Single.
    Select Single requires one communication with the database system, whereas Select-Endselect needs two.
    Select Statements SQL Interface
    1.     Use column updates instead of single-row updates
    to update your database tables.
    SELECT * FROM SFLIGHT INTO SFLIGHT_WA.
      SFLIGHT_WA-SEATSOCC =
        SFLIGHT_WA-SEATSOCC - 1.
      UPDATE SFLIGHT FROM SFLIGHT_WA.
    ENDSELECT.
    The above mentioned code can be more optimized by using the following code
    UPDATE SFLIGHT
           SET SEATSOCC = SEATSOCC - 1.
    2.     For all frequently used Select statements, try to use an index.
    SELECT * FROM SBOOK CLIENT SPECIFIED INTO SBOOK_WA
      WHERE CARRID = 'LH'
        AND CONNID = '0400'.
    ENDSELECT.
    The above mentioned code can be more optimized by using the following code
    SELECT * FROM SBOOK CLIENT SPECIFIED INTO SBOOK_WA
      WHERE MANDT IN ( SELECT MANDT FROM T000 )
        AND CARRID = 'LH'
        AND CONNID = '0400'.
    ENDSELECT.
    3.     Using buffered tables improves the performance considerably.
    Bypassing the buffer increases the network considerably
    SELECT SINGLE * FROM T100 INTO T100_WA
      BYPASSING BUFFER
      WHERE     SPRSL = 'D'
            AND ARBGB = '00'
            AND MSGNR = '999'.
    The above mentioned code can be more optimized by using the following code
    SELECT SINGLE * FROM T100  INTO T100_WA
      WHERE     SPRSL = 'D'
            AND ARBGB = '00'
            AND MSGNR = '999'.
    Select Statements  Aggregate Functions
    •     If you want to find the maximum, minimum, sum and average value or the count of a database column, use a select list with aggregate functions instead of computing the aggregates yourself.
    Some of the Aggregate functions allowed in SAP are  MAX, MIN, AVG, SUM, COUNT, COUNT( * )
    Consider the following extract.
                Maxno = 0.
                Select * from zflight where airln = ‘LF’ and cntry = ‘IN’.
                 Check zflight-fligh > maxno.
                 Maxno = zflight-fligh.
                Endselect.
    The  above mentioned code can be much more optimized by using the following code.
    Select max( fligh ) from zflight into maxno where airln = ‘LF’ and cntry = ‘IN’.
    Select Statements  For All Entries
    •     The for all entries creates a where clause, where all the entries in the driver table are combined with OR. If the number of entries in the driver table is larger than rsdb/max_blocking_factor, several similar SQL statements are executed to limit the length of the WHERE clause.
         The plus
    •     Large amount of data
    •     Mixing processing and reading of data
    •     Fast internal reprocessing of data
    •     Fast
         The Minus
    •     Difficult to program/understand
    •     Memory could be critical (use FREE or PACKAGE size)
    Points to be must considered FOR ALL ENTRIES
    •     Check that data is present in the driver table
    •     Sorting the driver table
    •     Removing duplicates from the driver table
    Consider the following piece of extract
              Loop at int_cntry.
      Select single * from zfligh into int_fligh
      where cntry = int_cntry-cntry.
      Append int_fligh.
                          Endloop.
    The above mentioned can be more optimized by using the following code.
    Sort int_cntry by cntry.
    Delete adjacent duplicates from int_cntry.
    If NOT int_cntry[] is INITIAL.
                Select * from zfligh appending table int_fligh
                For all entries in int_cntry
                Where cntry = int_cntry-cntry.
    Endif.
    Select Statements Select Over more than one Internal table
    1.     Its better to use a views instead of nested Select statements.
    SELECT * FROM DD01L INTO DD01L_WA
      WHERE DOMNAME LIKE 'CHAR%'
            AND AS4LOCAL = 'A'.
      SELECT SINGLE * FROM DD01T INTO DD01T_WA
        WHERE   DOMNAME    = DD01L_WA-DOMNAME
            AND AS4LOCAL   = 'A'
            AND AS4VERS    = DD01L_WA-AS4VERS
            AND DDLANGUAGE = SY-LANGU.
    ENDSELECT.
    The above code can be more optimized by extracting all the data from view DD01V_WA
    SELECT * FROM DD01V INTO  DD01V_WA
      WHERE DOMNAME LIKE 'CHAR%'
            AND DDLANGUAGE = SY-LANGU.
    ENDSELECT
    2.     To read data from several logically connected tables use a join instead of nested Select statements. Joins are preferred only if all the primary key are available in WHERE clause for the tables that are joined. If the primary keys are not provided in join the Joining of tables itself takes time.
    SELECT * FROM EKKO INTO EKKO_WA.
      SELECT * FROM EKAN INTO EKAN_WA
          WHERE EBELN = EKKO_WA-EBELN.
      ENDSELECT.
    ENDSELECT.
    The above code can be much more optimized by the code written below.
    SELECT PF1 PF2 FF3 FF4 INTO TABLE ITAB
        FROM EKKO AS P INNER JOIN EKAN AS F
          ON PEBELN = FEBELN.
    3.     Instead of using nested Select loops it is often better to use subqueries.
    SELECT * FROM SPFLI
      INTO TABLE T_SPFLI
      WHERE CITYFROM = 'FRANKFURT'
        AND CITYTO = 'NEW YORK'.
    SELECT * FROM SFLIGHT AS F
        INTO SFLIGHT_WA
        FOR ALL ENTRIES IN T_SPFLI
        WHERE SEATSOCC < F~SEATSMAX
          AND CARRID = T_SPFLI-CARRID
          AND CONNID = T_SPFLI-CONNID
          AND FLDATE BETWEEN '19990101' AND '19990331'.
    ENDSELECT.
    The above mentioned code can be even more optimized by using subqueries instead of for all entries.
    SELECT * FROM SFLIGHT AS F INTO SFLIGHT_WA
        WHERE SEATSOCC < F~SEATSMAX
          AND EXISTS ( SELECT * FROM SPFLI
                         WHERE CARRID = F~CARRID
                           AND CONNID = F~CONNID
                           AND CITYFROM = 'FRANKFURT'
                           AND CITYTO = 'NEW YORK' )
          AND FLDATE BETWEEN '19990101' AND '19990331'.
    ENDSELECT.
    1.     Table operations should be done using explicit work areas rather than via header lines.
    READ TABLE ITAB INTO WA WITH KEY K = 'X‘ BINARY SEARCH.
    IS MUCH FASTER THAN USING
    READ TABLE ITAB INTO WA WITH KEY K = 'X'.
    If TAB has n entries, linear search runs in O( n ) time, whereas binary search takes only O( log2( n ) ).
    2.     Always try to use binary search instead of linear search. But don’t forget to sort your internal table before that.
    READ TABLE ITAB INTO WA WITH KEY K = 'X'. IS FASTER THAN USING
    READ TABLE ITAB INTO WA WITH KEY (NAME) = 'X'.
    3.     A dynamic key access is slower than a static one, since the key specification must be evaluated at runtime.
    4.     A binary search using secondary index takes considerably less time.
    5.     LOOP ... WHERE is faster than LOOP/CHECK because LOOP ... WHERE evaluates the specified condition internally.
    LOOP AT ITAB INTO WA WHERE K = 'X'.
    ENDLOOP.
    The above code is much faster than using
    LOOP AT ITAB INTO WA.
      CHECK WA-K = 'X'.
    ENDLOOP.
    6.     Modifying selected components using “ MODIFY itab …TRANSPORTING f1 f2.. “ accelerates the task of updating  a line of an internal table.
    WA-DATE = SY-DATUM.
    MODIFY ITAB FROM WA INDEX 1 TRANSPORTING DATE.
    The above code is more optimized as compared to
    WA-DATE = SY-DATUM.
    MODIFY ITAB FROM WA INDEX 1.
    7.     Accessing the table entries directly in a "LOOP ... ASSIGNING ..." accelerates the task of updating a set of lines of an internal table considerably
    Modifying selected components only makes the program faster as compared to Modifying all lines completely.
    e.g,
    LOOP AT ITAB ASSIGNING <WA>.
      I = SY-TABIX MOD 2.
      IF I = 0.
        <WA>-FLAG = 'X'.
      ENDIF.
    ENDLOOP.
    The above code works faster as compared to
    LOOP AT ITAB INTO WA.
      I = SY-TABIX MOD 2.
      IF I = 0.
        WA-FLAG = 'X'.
        MODIFY ITAB FROM WA.
      ENDIF.
    ENDLOOP.
    8.    If collect semantics is required, it is always better to use to COLLECT rather than READ BINARY and then ADD.
    LOOP AT ITAB1 INTO WA1.
      READ TABLE ITAB2 INTO WA2 WITH KEY K = WA1-K BINARY SEARCH.
      IF SY-SUBRC = 0.
        ADD: WA1-VAL1 TO WA2-VAL1,
             WA1-VAL2 TO WA2-VAL2.
        MODIFY ITAB2 FROM WA2 INDEX SY-TABIX TRANSPORTING VAL1 VAL2.
      ELSE.
        INSERT WA1 INTO ITAB2 INDEX SY-TABIX.
      ENDIF.
    ENDLOOP.
    The above code uses BINARY SEARCH for collect semantics. READ BINARY runs in O( log2(n) ) time. The above piece of code can be more optimized by
    LOOP AT ITAB1 INTO WA.
      COLLECT WA INTO ITAB2.
    ENDLOOP.
    SORT ITAB2 BY K.
    COLLECT, however, uses a hash algorithm and is therefore independent
    of the number of entries (i.e. O(1)) .
    9.    "APPEND LINES OF itab1 TO itab2" accelerates the task of appending a table to another table considerably as compared to “ LOOP-APPEND-ENDLOOP.”
    APPEND LINES OF ITAB1 TO ITAB2.
    This is more optimized as compared to
    LOOP AT ITAB1 INTO WA.
      APPEND WA TO ITAB2.
    ENDLOOP.
    10.   “DELETE ADJACENT DUPLICATES“ accelerates the task of deleting duplicate entries considerably as compared to “ READ-LOOP-DELETE-ENDLOOP”.
    DELETE ADJACENT DUPLICATES FROM ITAB COMPARING K.
    This is much more optimized as compared to
    READ TABLE ITAB INDEX 1 INTO PREV_LINE.
    LOOP AT ITAB FROM 2 INTO WA.
      IF WA = PREV_LINE.
        DELETE ITAB.
      ELSE.
        PREV_LINE = WA.
      ENDIF.
    ENDLOOP.
    11.   "DELETE itab FROM ... TO ..." accelerates the task of deleting a sequence of lines considerably as compared to “  DO -DELETE-ENDDO”.
    DELETE ITAB FROM 450 TO 550.
    This is much more optimized as compared to
    DO 101 TIMES.
      DELETE ITAB INDEX 450.
    ENDDO.
    12.   Copying internal tables by using “ITAB2[ ] = ITAB1[ ]” as compared to “LOOP-APPEND-ENDLOOP”.
    ITAB2[] = ITAB1[].
    This is much more optimized as compared to
    REFRESH ITAB2.
    LOOP AT ITAB1 INTO WA.
      APPEND WA TO ITAB2.
    ENDLOOP.
    13.   Specify the sort key as restrictively as possible to run the program faster.
    “SORT ITAB BY K.” makes the program runs faster as compared to “SORT ITAB.”
    Internal Tables         contd…
    Hashed and Sorted tables
    1.     For single read access hashed tables are more optimized as compared to sorted tables.
    2.      For partial sequential access sorted tables are more optimized as compared to hashed tables
    Hashed And Sorted Tables
    Point # 1
    Consider the following example where HTAB is a hashed table and STAB is a sorted table
    DO 250 TIMES.
      N = 4 * SY-INDEX.
      READ TABLE HTAB INTO WA WITH TABLE KEY K = N.
      IF SY-SUBRC = 0.
      ENDIF.
    ENDDO.
    This runs faster for single read access as compared to the following same code for sorted table
    DO 250 TIMES.
      N = 4 * SY-INDEX.
      READ TABLE STAB INTO WA WITH TABLE KEY K = N.
      IF SY-SUBRC = 0.
      ENDIF.
    ENDDO.
    Point # 2
    Similarly for Partial Sequential access the STAB runs faster as compared to HTAB
    LOOP AT STAB INTO WA WHERE K = SUBKEY.
    ENDLOOP.
    This runs faster as compared to
    LOOP AT HTAB INTO WA WHERE K = SUBKEY.
    ENDLOOP.

  • Batch Query takes too much time

    Hi All,
    A query as simple as
    select * from ibt1 where batchnum = 'AAA'
    takes around 180 seconds to give results. if I replace batchnum condition with itemcode or anything other than batchnum, the same query returns results in some 5 seconds. the IBT1 table has nearly 3 lac rows. Consequently, a little complex query involving batchnm conditions gives 'query execution time out' error.
    what could be the reason? any resolution?
    Thanks,
    Binita

    Hello Binita,
    You need some database tunning....
    The IBT1 table has complex index on ItemCode, BatchNum, LineNum, WhsCode, and has no index on bacthnumber. But it has statistics, and statistics are useful for running queries ( see [ms technet here|http://technet.microsoft.com/hu-hu/library/cc966419(en-us).aspx]). Also there is a note about performance tunning databases 783183 .
    There is 2 ways to "speed up" your query: indexes and statistics
    Statistics
    See the statistics of IBT1 table:
    exec SP_HELPSTATS 'IBT1','ALL'
    the result set you see : the statistics name ([IBT1_PRIMARY]  and some statistics created by the system name likes WASys_XXXX. For Batchnum, you can execute the following statement:
    DBCC SHOW_STATISTICS ('IBT1',_WA_Sys_00000002_4EE969DE)
    --where _WA_Sys_00000002_4EE969DE is the name of the statistics of batchnum
    Check the resultset. If the "updated", "rows","row sampled" columns. If necessary, you can update the statistics by:
    -- update statistics on whole database
    EXEC SP_UPDATESTATS
    -- update all statistics of IBT1 table
    UPDATE STATISTICS IBT1 WITH FULLSCAN
    -- update a specific statistics of IBT1 table
    UPDATE STATISTICS IBT1(_WA_Sys_00000002_4EE969DE) WITH FULLSCAN
    Index defragmentation/reindex
    If the index not contiguous, the seeking inside several fragmented files takes more time.
    Execute your query in Management Studio Query analizer, and trun on Excution plans (CTRLL or CTRLM). This shows the compute cost of the query.
    select * from ibt1 where batchnum = 'AAA'
    result will be [IBT1_PRIMARY]  index scan.  You can check the fragmentation of the primary index of IBT1 table:
    DBCC SHOWCONTIG ('IBT1') WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS
    In the resultset the column ScanDensity shows the fragmentation percent, This value is 100 if everything is contiguous; if this value is less than 100, some fragmentation exists.
    Reindex can be done by the following statement:
    DBCC DBREINDEX ('IBT1','IBT1_PRIMARY',100) WITH NO_INFOMSGS
    Take care: all statements should NOT be execute during business hours.
    This may helps you.
    Regards,
    J.

Maybe you are looking for

  • Blue Screen and Sound Problems, In Desperate Need of Assistance

    About a week and a half ago, my computer officially stopped showing anything on the display when I tried to start it up. It had been doing it on and off for a long time, but I would eventually get it to display. Not this time... My husband and I took

  • Syncing Documents between MacBook & 1st gen iPad

    Is there any way for me to access documents on my MacBook Pro on my first generation iPad?  My MacBook came with the Preview program that allows you save highlighting...is there a similar app for iPad?

  • Non-printing repeating meetings

    OK, this is downright weird. I have a user (an executive, of course) whose calendar does not print all events when [a] printing from Outlook and printing from a Delegate/Editor/Designate window. In this case, only repeating events are printed. But wa

  • I5 apps will not update after 8.1 install

    Unable to get any app updates to run after 8.1 iOS install. Have tried using LTE or WiFi only, Reset Network Settings, power cycled device which is an i5. Any ideas? I have also tried updating one app at a time with same results....circle with dot in

  • Crystal Reports addon  client installation

    When I try to install de add-on in customer machine an error appear that the exe installation file of crystal reports does not exist, In the server there is not a problem only with the client workstation Mauricio Rodriguez