OPtimizing Performance for Select query on huge table

Hi All,
   We are fetching a single record from NAST table. The table has around 10 Million Entries.
   The Select Query takes around 5-6 minutes to return.
   We are not using the Primary key completely. We are using only one field of the primary key.
    The field is also a part of the Index but we are not using all the fields in the index as well.
    We need to bring down the time. What can be the solution? I cant see any changes to the code, since its a single query and we cant use the Entire Primary key.
   Would creating an Index on the fields that we are concerned with help in this regard.
   Open to all solutions.
Thanks in Advance,
Imran

There are sometimes tricks you can use to get it to use the index more efficiently. If you let us know which fields you are using in the SELECT (all of them actually), we might be able to help.
Or are you saying you can't change the code at all?
Please don't create duplicate posts though.
Rob
Message was edited by:
        Rob Burbank

Similar Messages

  • OPtimizing Performance for Select query on NAST table

    Hi All,
       We are fetching a single record from NAST table. The table has around 10 Million Entries.
       The Select Query takes around 5-6 minutes to return.
       We are not using the Primary key completely. We are using only one field of the primary key.
        The field is also a part of the Index but we are not using all the fields in the index as well.
        We need to bring down the time. What can be the solution? I cant see any changes to the code, since its a single query and we cant use the Entire Primary key.
       Would creating an Index on the fields that we are concerned with help in this regard.
       Open to all solutions.
    Thanks in Advance,
    Imran

    Hi,
    Please check this thread
    http://sap.ittoolbox.com/documents/popular-q-and-a/specifying-the-index-to-be-used-2462
    For creating another secondary index in NAST whether basis will approve for this?
    aRs

  • Select query on a table with 13 million of rows

    Hi guys,
    I have been trying to perform a select query on a table which has 13 millions of entries however it took around 58 min to complete.
    The table has 8 columns with 4 Primary keys looks like below:
    (PK) SegmentID > INT
    (PK) IPAddress > VARCHAR (45)
    MAC Address > VARCHAR (45)
    (PK) Application Name > VARCHAR (45)
    Total Bytes > INT
    Dates > VARCHAR (45)
    Times > VARCHAR (45)
    (PK) DateTime > DATETIME
    The sql query format is :
    select ipaddress, macaddress, sum(totalbytes), applicationname , dates,
    times from appstat where segmentid = 1 and datetime between '2011-01-03
    15:00:00.0' and '2011-01-04 15:00:00.0' group by ipaddress,
    applicationname order by applicationname, sum(totalbytes) desc
    Is there a way I can improve this query to be faster (through my.conf or any other method)?
    Any feedback is welcomed.
    Thank you.
    Mus

    Tolls wrote:
    What db is this?
    You never said.
    Anyway, it looks like it's using the Primary Key to find the correct rows.
    Is that the correct number of rows returned?
    5 million?
    Sorted?I am using MySQL. By the way, the query time has been much more faster (22 sec) after I changed the configuration file (based on my-huge.cnf).
    The number of rows returned is 7999 Rows
    This is some portion of the my.cnf
    # The MySQL server
    [mysqld]
    port = 3306
    socket = /var/lib/mysql/mysql.sock
    skip-locking
    key_buffer = 800M
    max_allowed_packet = 1M
    table_cache = 256
    sort_buffer_size = 1M
    read_buffer_size = 1M
    read_rnd_buffer_size = 4M
    myisam_sort_buffer_size = 64M
    thread_cache_size = 8
    query_cache_size= 16M
    log = /var/log/mysql.log
    log-slow-queries = /var/log/mysqld.slow.log
    long_query_time=10
    # Try number of CPU's*2 for thread_concurrency
    thread_concurrency = 6
    Is there anything else I need to tune so it can be faster ?
    Thanks a bunch.
    Edited by: user578505 on Jan 17, 2011 6:47 PM

  • Creating SELECT query between 3 tables

    Hi there,
    Im trying to create a SELECT query between 3 tables and it is driving me round the bend.
    I have 3 tables connected together which are:
    MODUL
    modulid
    modulname
    modulevel
    STUDENT
    studentid
    surname
    inits
    s e x
    phone
    email
    logon
    STUDREGOCCUR
    modulid
    acyear
    semester
    occletter
    studentid
    result
    I want to select the fields surname, inits, studentid from the STUDENT table, modulname from the MODUL table and result from my STUDREGOCCUR table that is NOT NULL.
    I have tried SELECT STUDENT.STUDENTID, STUDENT.INITS, STUDENT.SURNAME, MODUL.MODULNAME, STUDREGOCCUR.RESULT WHERE STUDREGOCCUR.RESULT IS NOT NULL;
    I have also tried many other ways and done research hwich hasnt really helped me unfortunately.
    Im quite new to SELECT queries and im not sure where im going wrong, i would greatly appreciate if someone could help me solve my problem.
    Thanks for the help :)
    Edited by: user633643 on 06-Dec-2008 08:09

    If you want data from multiple tables you would need to perform a join. The general form would be:
    select t1.cola, t2.col2, t3.col.x
    from table_a a, table_b b, table_c c
    where a.key = b.key
    and b.key = c.key
    or perhaps c relates back directly to a so it is a.key = c.key where key can be any column whose value is equilivent in what it represents to the value it is being compared to, that is, student_number = student_number or the columns regardless of name are both building numbers, room numbers, etc ....
    This is not your exact solution but it should help.
    HTH -- Mark D Powell --

  • CV04N takes long time to process select query on DRAT table

    Hello Team,
    While using CV04N to display DIR's, it takes long time to process select query on DRAT table. This query includes all the key fields. Any idea as to how to analyse this?
    Thanks and best regards,
    Bobby
    Moderator message: please read the sticky threads of this forum, there is a lot of information on what you can do.
    Edited by: Thomas Zloch on Feb 24, 2012

    Be aware that XP takes approx 1gb of your RAM leaving you with 1gb for whatever else is running. MS Outlook is also a memory hog.
    To check Virtual Memory Settings:
    Control Panel -> System
    System Properties -> Advanced Tab -> Performance Settings
    Performance Options -> Adavanced Tab - Virtual Memory section
    Virtual Memory -
    what are
    * Initial Size
    * Maximum Size
    In a presentation at one of the Hyperion conferences years ago, Mark Ostroff suggested that the initial be set to the same as Max. (Max is typically 2x physical RAM)
    These changes may provide some improvement.

  • How to perform a select op on a table whose name is contained by a variable

    I am using Oracle SQL*Plus client.
    declare
    tablename_var varchar(10); LOOK HERE
    date_var date;
    begin
    select sysdate
    into date_var
    from &tablename_var; LOOK HERE
    dbms_output.put_line('The system date is '||date_var);
    end;
    The above code prompts the user to enter a value for the variable tablename_var, once the user enters 'dual' on prompt... The system date is given as output.
    declare
    tablename_var varchar(10):='dual'; LOOK HERE
    date_var date;
    begin
    select sysdate
    into date_var
    from tablename_var; LOOK HERE
    dbms_output.put_line('The system date is '||date_var);
    end;
    This code fails and gives an error. I understand. Engine interprets it as... trying to perform a select operation on a variable, and says a table or a view is expected.
    Can someone please tell me what to do, to perform a select operation on a table whose name is contained by a variable, like above?

    Hi,
    Welcome to the forum!
    You need Dynamic SQL if the table- or column names are variables.
    Getting the current date isn't a good example; you could get that without a query simply by saying
    date_var := SYSDATE;Also, SELECT ... INTO will raise an error if the query does not return exactly 1 row.
    In the example below, let's get the latest entry_date from a given table:
    For example:
    declare
         tablename_var     varchar(10);
         date_var      date;
         sql_txt           VARCHAR2 (1000);
    begin
         tablename_var := 'table_x;
         sql_txt := 'select  MAX (entrydate)'
              || '  from  ' || tablename_var;
         dbms_output.put_line (sql_txt || ' = sql_txt');    -- Not essential, but recommended
         EXECUTE IMMEDIATE  sql_txt  INTO date_var;
         dbms_output.put_line ('The latest entry_date is ' || date_var);
    end;Dynamic SQL involves creating a string that contains the SQL statement. Displaying the string is purely optional, of course, but it's a very good idea when writing and de-bugging code. Remember to comment-out or delete the display before moving the code into Production.
    For an exercise, make the column name a variable, instead of the hard-coded entry_date.
    Edited by: Frank Kulash on Nov 5, 2009 9:20 AM

  • Is it worth using select query on infotype tables

    Hi Experts,
    I might be posting in the wrong column, but i just need to know is it worth using a select query on Infotype tables (PAxxxx)?? or should we prefer using the function modules for data fetching?
    If select is not suggested, what is the reason for that?
    Rgds
    Prateek

    Hi ,
    Its not said that u cant write select on PAXXXX tables . Yes of couse LDB are there to fetch the data but it depends on
    the requirement when to write a select and when to consider using in LDB .
    Generally when you are looking at say 8 to 10 tables of infotypes with free selection , then LDB is suggested to fetch the data .
    if you are looking to fetch the data for say some tables for a restricted selection (where clause) then select is used .
    If i want to write a program using select only then fetching data from infotypes tables for large no of records will lead to
    more time consumption which becomes easier in LDB as they are fetched in hierarchy level based on keys .
    Normally it will be a combination of LDB and select querys  in the development scenario
    Br,
    Vijay.

  • Select Query on TCURR table

    Hello All,
    I am writing select query on TCURR table , but unable to get the values from table though i cansee the entries in table for the same condition as i provided int he program .
    Is there an peculiar reason for the sme .
    MY query is as follows.
    SELECT  * FROM tcurr INTO TABLE g_t_tcurr
                                     WHERE kurst = 'M'                             AND fcurr = g_f_waers
                                 AND tcurr = 'AUD'
                                 AND gdatu LE l_f_datum (MKPF-BUDAT).
    Any help is appreciated .
    Thanks

    Hi,
    Please check the datatype and try again...
    data:
             DATC(8)       TYPE C,
             GDATU_OLD(8)  TYPE C.
    *exc_type = 'M'.
    SELECT * FROM  tcurf  into table g_t_tcurr
    CLIENT SPECIFIED
               WHERE  kurst       = exc_type
               AND    fcurr       = for_curr
               AND    tcurr       = loc_curr
               AND    gdatu      GE datc
               AND    mandt       = mandt
               ORDER BY PRIMARY KEY.
    FM: CONVERT_TO_LOCAL_CURRENCY_N can be used to convert the amt from local currency to Foreign currency.
    Regds
    Parvathi

  • How to insert the select query result into table?

    How to insert the select query result into table?
    SELECT  top 20 creation_time  
            ,last_execution_time 
            ,total_physical_reads
            ,total_logical_reads  
            ,total_logical_writes
            , execution_count 
            , total_worker_time
            , total_elapsed_time 
            , total_elapsed_time / execution_count avg_elapsed_time
            ,SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
             ((CASE statement_end_offset 
              WHEN -1 THEN DATALENGTH(st.text)
              ELSE qs.statement_end_offset END 
                - qs.statement_start_offset)/2) + 1) AS statement_text
    FROM sys.dm_exec_query_stats AS qs
    CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
    ORDER BY total_elapsed_time / execution_count DESC;
    Thanks,
    Tirumala

    1. SELECT INTO
    Below method will create table when data is inserted from one table to another table. Its useful when you need exactly same datatype as source table.
    Use AdventureWorks2008R2;
    Go
    ---Insert data using SELECT INTO
    SELECT AddressLine1, City
    INTO BothellAddresses
    FROM Person.Address
    where City = 'Bothell';
    GO
    ---VERIFY DATA
    Select AddressLine1, City
    FROM BothellAddresses
    ---DROP TABLE
    DROP TABLE BothellAddresses
    GO
    2. INSERT INTO SELECT
    Below method will need table to be created prior to inserting data. Its really useful when table is already created and you want insert data from
    another table.
    Use AdventureWorks2008R2;
    Go
    ---Create Table
    CREATE TABLE BothellAddresses (AddressLine1 NVARCHAR(60), City NVARCHAR(30))
    ---Insert into above table using SELECT
    INSERT INTO BothellAddresses(AddressLine1, City)
    SELECT AddressLine1, City
    FROM Person.Address
    where City = 'Bothell';
    ---VERIFY DATA
    Select AddressLine1, City
    FROM BothellAddresses
    ---DROP TABLE
    DROP TABLE BothellAddresses
    GO
    Regards,
    Vishal Patel
    Blog: http://vspatel.co.uk
    Site: http://lehrity.com

  • Dynamic Select Query including Dynamic Tables with For all Entries

    Hello everyone,
    I need to create a select query which involves using of Dynamic Tables.
    Suppose I have a dynamic table <d1> which consist of let say 10 records.
    Now i need to make a select query putting data into another dynamic table <d2>
    CONCATENATE keyfield '=' '<d1>' INTO g_condition SEPARATED BY space.
    CONCATENATE g_condition '-' keyfield INTO g_condition.
    SELECT * FROM (wa_all_tables-name) INTO CORRESPONDING FIELDS OF TABLE <d1>
            FOR ALL ENTRIES IN <d1>
    WHERE (g_condition).
    But it is giving dump.
    Please help me on this....

    Short text
        A condition specified at runtime has an unexpected format.
    What happened?
        Error in the ABAP Application Program
        The current ABAP program "ZNG_CUSTOMWRITE" had to be terminated because it has
        come across a statement that unfortunately cannot be executed.
    Error analysis
        An exception occurred that is explained in detail below.
        The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SEMANTICS', was
         not caught in
        procedure "WRITE_ARCHIVE_PROD" "(FORM)", nor was it propagated by a RAISING
         clause.
        Since the caller of the procedure could not have anticipated that the
        exception would occur, the current program is terminated.
        The reason for the exception is:
        The current ABAP program has tried to execute an Open SQL statement
        which contains a WHERE, ON or HAVING condition with a dynamic part.
        The part of the WHERE, ON or HAVING condition specified at runtime in
        a field or an internal table, contains the invalid value "ZCOURIER-ZCOURIERID".
    CONCATENATE keyfield '=' g_header INTO g_condition SEPARATED BY space.
    CONCATENATE g_condition '-' keyfield INTO g_condition.
    SELECT * FROM (wa_all_tables-name) INTO CORRESPONDING FIELDS OF TABLE <dyn_table1>
    FOR ALL ENTRIES IN <dyn_table>
      WHERE (g_condition).

  • How to assign table name for select query in loop.

    Hi friends my requirement is count the no of records of all the database table which comes into an internal table ."Check the below coding". Iam  fetching the tables from dd03l table into an internal table .plz give me a sujjesion how to assign a table name in select query  in a loop.
      SELECT tabname FROM dd09l
                INTO TABLE i_dd09l
                WHERE protokoll = 'X'.
      IF sy-subrc = 0.
        SORT i_dd09l BY tabname.
      ENDIF.
      LOOP AT i_dd09l.
        SELECT COUNT(*) INTO val FROM i_dd09l-tabname.
        IF sy-subrc = 0.
          i_dd09l-count = val.
        ENDIF.
        MODIFY i_dd09l INDEX sy-index.
        CLEAR val.
      ENDLOOP.
    error : 'I_DD09L-TABNAME' is not defined in the abap dictionary as a table.

    data: dy_table type ref to data,
          dy_line type ref to data,
          xfc type lvc_s_fcat,
          ifc type lvc_t_fcat,
          dy_field type ref to data.
    LOOP AT i_dd09l.
    perform get_structure using i_dd09l-tabname .
    CREATE DATA dy_table TYPE TABLE OF (_dd09l-tab_name).
        UNASSIGN <dyn_table>.
        ASSIGN dy_table->* TO <dyn_table>.
    SELECT COUNT(*) INTO val FROM <dyn_table>.
    IF sy-subrc = 0.
    i_dd09l-count = val.
    ENDIF.
    MODIFY i_dd09l INDEX sy-index.
    CLEAR val.
    ENDLOOP.
    form get_structure using p_table.
      data : idetails type abap_compdescr_tab,
      xdetails type abap_compdescr.
      data : ref_table_des type ref to cl_abap_structdescr.
    Get the structure of the table.
      ref_table_des ?=
      cl_abap_typedescr=>describe_by_name( p_table ).
      idetails = ref_table_des->components.
      loop at idetails into xdetails.
        clear xfc.
        xfc-fieldname = xdetails-name .
        xfc-datatype = xdetails-type_kind.
        xfc-inttype = xdetails-type_kind.
        xfc-intlen = xdetails-length.
        xfc-decimals = xdetails-decimals.
        append xfc to ifc.
      endloop.
    endform.                    "get_structure
    Try like this hope it will work.
    Regards,
    madan.

  • Performance improvement for select query

    Hi all,
    need to improve performace for the below select query as it is taking long time
    SELECT vbeln pdstk
             FROM vbuk INTO TABLE it_vbuk1 FOR ALL ENTRIES IN it_likp
          WHERE vbeln = it_likp-vbeln       AND
                wbstk = 'C'  AND "pdstk = ' ' AND
                vbtyp IN gr_delivery AND
                ( fkstk = 'A' OR fkstk = 'B' ) OR
                ( fkivk = 'A' OR fkivk = 'B' ).
    Regards,
    Kumar

    Hi,
        Check if it_likp is sorted on vbeln.
    SELECT vbeln pdstk
    FROM vbuk INTO TABLE it_vbuk1 FOR ALL ENTRIES IN it_likp
    WHERE vbeln = it_likp-vbeln AND
    wbstk = 'C' AND
    vbtyp IN gr_delivery AND
    ( ( fkstk = 'A' OR fkstk = 'B' ) OR      <-- check this condition , if ( ) is needed ...
      ( fkivk = 'A' OR fkivk = 'B' ) ) .
    Regards,
    Srini.

  • Regarding to perform in select query

    could any tell  the select query in this piece of code would affect the performance of the programe
    DATA: BEGIN OF OUTREC,
          BANKS LIKE BNKA-BANKS,
          BANKL LIKE BNKA-BANKL,
          BANKA LIKE BNKA-BANKA,
          PROVZ LIKE BNKA-PROVZ,   "Region (State, Province, County)
          BRNCH LIKE BNKA-BRNCH,
          STRAS LIKE BNKA-STRAS,
          ORT01 LIKE BNKA-ORT01,
          SWIFT LIKE BNKA-SWIFT,
    END OF OUTREC.
    OPEN DATASET P_OUTPUT FOR OUTPUT IN TEXT MODE.
    IF SY-SUBRC NE 0. EXIT. ENDIF.
    SELECT * FROM BNKA
             WHERE BANKS EQ P_BANKS
             AND   LOEVM NE 'X'
             AND   XPGRO NE 'X'
             ORDER BY BANKS BANKL.
      PERFORM TRANSFER_DATA.
    ENDSELECT.
    CLOSE DATASET P_OUTPUT.
    *&      Transfer the data to the output file
    FORM TRANSFER_DATA.
      OUTREC-BANKS = BNKA-BANKS.
      OUTREC-BANKL = BNKA-BANKL.
      OUTREC-BANKA = BNKA-BANKA.
      OUTREC-PROVZ = BNKA-PROVZ.
      OUTREC-BRNCH = BNKA-BRNCH.
      OUTREC-STRAS = BNKA-STRAS.
      OUTREC-ORT01 = BNKA-ORT01.
      OUTREC-SWIFT = BNKA-SWIFT.
      TRANSFER OUTREC TO P_OUTPUT.
    ENDFORM.                               " READ_IN_DATA

    Hi
    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.
    Points # 1/2
    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
    2.     Select all the records in a single shot using into table clause of select statement rather than to use Append statements.
    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.
    4.     For testing existence , use Select.. Up to 1 rows statement instead of a Select-Endselect-loop with an Exit. 
    5.     Use Select Single if all primary key fields are supplied in the Where condition .
    Point # 1
    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.
    Point # 2
    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'.
    Point # 3
    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.
    Point # 4
    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.
    Point # 5
    If all primary key fields are supplied in the Where condition you can even use Select Single.
    Select Single requires one communication with the database system, whereas Select-Endselect needs two.
    Select Statements           contd..  SQL Interface
    1.     Use column updates instead of single-row updates
    to update your database tables.
    2.     For all frequently used Select statements, try to use an index.
    3.     Using buffered tables improves the performance considerably.
    Point # 1
    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.
    Point # 2
    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.
    Point # 3
    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       contd…           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    contd…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    contd…  Select Over more than one Internal table
    1.     Its better to use a views instead of nested Select statements.
    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.
    3.     Instead of using nested Select loops it is often better to use subqueries.
    Point # 1
    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
    Point # 2
    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.
    Point # 3
    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.
    2.     Always try to use binary search instead of linear search. But don’t forget to sort your internal table before that.
    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.
    6.     Modifying selected components using “ MODIFY itab …TRANSPORTING f1 f2.. “ accelerates the task of updating  a line of an internal table.
    Point # 2
    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 ) ).
    Point # 3
    READ TABLE ITAB INTO WA WITH KEY K = 'X'. IS FASTER THAN USING
    READ TABLE ITAB INTO WA WITH KEY (NAME) = 'X'.
    Point # 5
    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.
    Point # 6
    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
    8.    If collect semantics is required, it is always better to use to COLLECT rather than READ BINARY and then ADD.
    9.    "APPEND LINES OF itab1 TO itab2" accelerates the task of appending a table to another table considerably as compared to “ LOOP-APPEND-ENDLOOP.”
    10.   “DELETE ADJACENT DUPLICATES“ accelerates the task of deleting duplicate entries considerably as compared to “ READ-LOOP-DELETE-ENDLOOP”.
    11.   "DELETE itab FROM ... TO ..." accelerates the task of deleting a sequence of lines considerably as compared to “  DO -DELETE-ENDDO”.
    Point # 7
    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.
    Point # 8
    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)) .
    Point # 9
    APPEND LINES OF ITAB1 TO ITAB2.
    This is more optimized as compared to
    LOOP AT ITAB1 INTO WA.
      APPEND WA TO ITAB2.
    ENDLOOP.
    Point # 10
    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.
    Point # 11
    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”.
    13.   Specify the sort key as restrictively as possible to run the program faster.
    Point # 12
    ITAB2[] = ITAB1[].
    This is much more optimized as compared to
    REFRESH ITAB2.
    LOOP AT ITAB1 INTO WA.
      APPEND WA TO ITAB2.
    ENDLOOP.
    Point # 13
    “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.

  • ST05 Trace on a select query on BSEG table

    hi all,
    this is my select query on table BSEG table:
      SELECT bukrs
             belnr
             gjahr
             buzei
             KOART
             mwskz
             kostl
             lifnr
             aufnr
             werks
             ebeln
             txjcd
             projk FROM bseg
                   INTO TABLE i_bseg
                   FOR ALL ENTRIES IN i_ad_tab
                  WHERE bukrs EQ i_ad_tab-bukrs  AND
                        belnr EQ i_ad_tab-belnr  AND
                        gjahr EQ i_ad_tab-gjahr.
    when i m doing SQL trace ST05 on this query and in the detail statement showed the following query
    SELECT
      "MANDT" , "BUKRS" , "BELNR" , "GJAHR" , "PAGENO" , "TIMESTMP" ,
      "PAGELG" , "VARDATA"
    FROM
      "RFBLG"
    WHERE
      "MANDT" = ? AND  "BUKRS" = ? AND  "BELNR" = ? AND  "GJAHR" = ?
    ORDER BY
      "MANDT" , "BUKRS" , "BELNR" , "GJAHR" , "PAGENO"
    what is RFBLG table in SE11, but could not find it.
    what is RFBLG?also, the above select query giving me performance issues.. the "for all entries" clause is used as per norms...
    please suggest a solution..

    hi
    good
    The famous BSEG table is a cluster table.
    It is as was correctly stated part of the Accounting Document Segment. It is part of the Pool cluster RFBLG and lives in the package: FBAS (Financial accounting 'Basis').
    You can't read a cluster table exactly the way you read a database (old speak, transparent table).
    You can use a program to read called RFPPWF05
    Note 435694: Display BSEG item by calling FB09D (modified FB09)
    Other possiblity: Other possibility: CALL DIALOG 'RF_ZEILEN_ANZEIGE', but since this is a dialog I don't think this would work.
    In any event go to FBAS Package (development class) to see your business objects, class library and functions.
    you must use keyfields bukrs , belnr, gjahr
    (so 1st select table bkpf) to select bseg.
    or use secondary index tables:
    bsas, bsis, bsik, bsak, bsid, bsad
    Regards,
    Raj.

  • Select query on QALS table taking around 4 secs to fetch one record

    Hi,
    I have one select query that takes around 4 secs to fetch one record. I would like to know if there are any ways to reduce the time taken for this select.
    SELECT
         b~prueflos
         b~matnr
         b~lagortchrg
         a~vdatum
         a~kzart
         a~zaehler
         a~vcode
         a~vezeiterf
         FROM qals AS b LEFT OUTER JOIN qave AS a ON
         bprueflos = aprueflos
         INTO TABLE t_qals1
         FOR ALL ENTRIES IN t_lgorts
          WHERE  matnr = t_lgorts-matnr
          AND    werk = t_lgorts-werks
          AND    lagortchrg = t_lgorts-lgort
          AND    stat35 = c_x
          AND    art IN (c_01,c_08).
    When I took the SQL trace, here I found other details :
    Column          No.Of Distinct Records
    MANDANT                                      2
    MATNR                                      2.954
    WERK                                          30
    STAT34                                         2
    HERKUNFT                                   5
    Analyze Method                    Sample 114.654 Rows
    Levels of B-Tree                                 2
    Number of leaf blocks                         1.126
    Number of distinct keys                      16.224
    Average leaf blocks per key                1
    Average data blocks per key               3
    Clustering factor                                  61.610
    Also note, This select query is using INDEX RANGE SCAN QALS~D.
    All the suggestions are welcome
    Regards,
    Vijaya

    Hi Rob,
    Its strange but, the table t_lgorts  has only ONE record
    MATNR  =  000000000500003463
    WERK = D133
    LAGORTCHRG   = 0001                                            
    I have also seen that for the above criteria the table QALS has 2266 records that satisfy this condition.
    I am not sure..but if we write the above query as subquery instead of Outer join..will it improve the performance?
    Will check it from my side too..
    Regards,
    Vijaya

Maybe you are looking for

  • Issue with SSRS Expression

    Hi all,  I am facing some issue with ssrs expression.  I used below expression to show sum of budget.  =Sum(  CDbl(Fields!Budget.Value)) When I preview the report it shows #Error in that textbox.  Please help me to fix this one , I am not getting whe

  • Photo advancement in active filter no longer behaves as in previous Lightroom versions

    MAC Tiger 10.4 with Lightroom V1.3, and discussion involves Lightroom software prior to V1.3 This might be hard to explain, but here it goes. There is a nice "feature" I used in versions prior to V1.3 and now it behaves different and erratic. The ste

  • Unfreezing of columns in ALV grid

    Hi, When ever I view the ODS data, the key field columns are always freezed. Each time I need to unfreeze using Settings--> column --> unfreeze columns. Please guide me to set "unfreeze column" as default. Thanks in advance Suhas

  • IMac G5 OSX 10.5.1 display flicker

    Coincidentally with the installation of Leopard, the menu bar on my wife's G5 iMac 20" developed an intermittent flicker. Very annoying but does not compromise performance. Might this be a software issue or heaven forbid a harbringer of hardware prob

  • SAP Smart Forms

    How can use multiple tables in SAMART FORM