Need help in Performance tuning for function...

Hi all,
I am using the below algorithm for calculating the Luhn Alogorithm to calculate the 15th luhn digit for an IMEI (Phone Sim Card).
But the below function is taking about 6 min for 5 million records. I had 170 million records in a table want to calculate the luhn digit for all of them which might take up to 4-5 hours.Please help me performance tuning (better way or better logic for luhn calculation) to the below function.
A wikipedia link is provided for the luhn algorithm below
Create or Replace FUNCTION AddLuhnToIMEI (LuhnPrimitive VARCHAR2)
      RETURN VARCHAR2
   AS
      Index_no     NUMBER (2) := LENGTH (LuhnPrimitive);
      Multiplier   NUMBER (1) := 2;
      Total_Sum    NUMBER (4) := 0;
      Plus         NUMBER (2);
      ReturnLuhn   VARCHAR2 (25);
   BEGIN
      WHILE Index_no >= 1
      LOOP
         Plus       := Multiplier * (TO_NUMBER (SUBSTR (LuhnPrimitive, Index_no, 1)));
         Multiplier := (3 - Multiplier);
         Total_Sum  := Total_Sum + TO_NUMBER (TRUNC ( (Plus / 10))) + MOD (Plus, 10);
         Index_no   := Index_no - 1;
      END LOOP;
      ReturnLuhn := LuhnPrimitive || CASE
                                         WHEN MOD (Total_Sum, 10) = 0 THEN '0'
                                         ELSE TO_CHAR (10 - MOD (Total_Sum, 10))
                                     END;
      RETURN ReturnLuhn;
   EXCEPTION
      WHEN OTHERS
      THEN
         RETURN (LuhnPrimitive);
   END AddLuhnToIMEI;
http://en.wikipedia.org/wiki/Luhn_algorithmAny sort of help is much appreciated....
Thanks
Rede

There is a not needed to_number function in it. TRUNC will already return a number.
Also the MOD function can be avoided at some steps. Since multiplying by 2 will never be higher then 18 you can speed up the calculation with this.
create or replace
FUNCTION AddLuhnToIMEI_fast (LuhnPrimitive VARCHAR2)
      RETURN VARCHAR2
   AS
      Index_no     pls_Integer;
      Multiplier   pls_Integer := 2;
      Total_Sum    pls_Integer := 0;
      Plus         pls_Integer;
      rest         pls_integer;
      ReturnLuhn   VARCHAR2 (25);
   BEGIN
      for Index_no in reverse 1..LENGTH (LuhnPrimitive) LOOP
         Plus       := Multiplier * TO_NUMBER (SUBSTR (LuhnPrimitive, Index_no, 1));
         Multiplier := 3 - Multiplier;
         if Plus < 10 then
            Total_Sum  := Total_Sum + Plus ;
         else
            Total_Sum  := Total_Sum + Plus - 9;
         end if;  
      END LOOP;
      rest := MOD (Total_Sum, 10);
      ReturnLuhn := LuhnPrimitive || CASE WHEN rest = 0 THEN '0' ELSE TO_CHAR (10 - rest) END;
      RETURN ReturnLuhn;
   END AddLuhnToIMEI_fast;
/My tests gave an improvement for about 40%.
The next step to try could be to use native complilation on this function. This can give an additional big boost.
Edited by: Sven W. on Mar 9, 2011 8:11 PM

Similar Messages

  • Need help in Performance tuning

    Hi All,
            I am facing some performance issues in my program.  The program taking a hell lot of time to execute and some times timing out without giving the out put.  This is a report program with ALV output.  It is handling mainly Sales related data.
           The program is fetching a huge volume of data from different tables and processing this bulk data inside the loops several times.  In most of the queries I am unable to supply all key fields, because my requirement is like that only.  I have many places in my program i am using inner loop and function modules inside loop etc.
            Any pointers on this will be a great help.
    Regards,
    Jijeesh P G

    1) Make sure that any READ or LOOP inside an outer LOOP accesses the inner table with an appropriate key (either using BINARY search when reading a standard table or using sorted/hashed tables for inner tables only). This helps in most cases.
    2) If the tables witdh is more than aprox. 30 bytes LOOP ASSIGNING <wa> may help a bit. Declare <wa> for each table separately using the tables line type (otherway type casting would cost some additional time).
    3) You may use FM SAPGUI_PROGRESS_INDICATOR in the outer loops to inform the user while he is waiting.
    4) A COMMIT from time to time will reset the measured time for timeout ( and therefore avoids timeouts - do NOT use without checking step 1) ).
    4) The programm may use virtual memory if a huge amount of data is selected ( I have seen dumps in due to the fact that nor more disk space was available). So  - if STEPS 1)-3) failed - look a the process for rollling in/out).

  • Need help with Performance Tuning

    Following query takes 8 secs. Any help will be appreciated
    SELECT SUM(FuturesMarketVal) FuturesMarketVal
    FROM (SELECT CASE WHEN null IS NULL THEN FuturesMarketVal
    ELSE DECODE(FUTURES_NAME, null, FuturesMarketVal, 0)
    END FuturesMarketVal
    FROM (SELECT SUM( (a.FUTURES_ALLOC * (NVL(b.Futures_EOD_Price,0)/100 - NVL(c.Futures_EOD_Price,0)/100) * a.CONTRACT_SIZE) / DECODE(a.CONTRACT_SIZE,100000,1,1000000,4,3000000,12,1) ) FuturesMarketVal,
    a.FUTURES_NAME
    FROM cms_futures_trans a,
    cms_futures_price b,
    cms_futures_price c
              Where c.history_date (+) = TO_DATE(fas_pas_pkg.get_weekday(to_date('12/30/2005') - 1),'mm/dd/yyyy')
              and a.FUTURES_NAME = b.FUTURES_NAME (+)
    AND a.trade_date < TO_DATE('12/30/2005','mm/dd/yyyy')
    AND b.history_date (+) = TO_DATE('12/30/2005','mm/dd/yyyy')
    AND a.FUTURES_NAME = c.FUTURES_NAME (+)
    GROUP BY a.FUTURES_NAME
    /

    Eric:
    But there are only 5 records in cms_futures_price and 10 in cms_futures_trans :-)
    OP:
    I'm not usre what you are trying to fo here, but a couple of comments.
    Since NULL IS NULL will always be true, you don;t really need the CASE statement. as it stands, your query will always return FuturesMarketVal. If the results are correct, then you can do without the DECODE as well.
    Why are you calling fas_pas_pkg.get_weekday with a constant value? Can you not just use whatever it returns as a constant instead of calling the function?
    Are you sure you need all those outer joins? They almost guarantee full scans of the outer joined tables.
    Perhaps if you post some representative data from the two tables and an explanation of what you are trying to accomplish someone may have a better idea.
    John

  • Performance tuning for new OFMW environment

    Hello
    We have just set up a new UAT environment entirely on all Oracle FMW latest products which includes:
    1) OS -RHEL V5
    2) WebCenter
    3) SOA Suite
    4) Database
    5) IDM
    6) HTTP Server
    7) WebLogic Server
    As as post infrastructure setup plan we need to to performance tuning as well. Shall we do only WLS performance tuning or we need to tune each and every product in order to get optimum results.
    Any guide? resource to help?
    Pls advice
    Regards
    Dev

    When you install the product soa-suite (and probably webcenter too) a prerequisite check is performed
    that gives information about packages and parameters that need to be adjusted on your operating system.
    For products that run on WebLogic Server you probably have to tune the JVM, examples can be found here:
    - http://middlewaremagic.com/weblogic/?p=6930 (discusses JRockit)
    - http://middlewaremagic.com/weblogic/?p=7083 (focuses on Coherence, but the considerations can be applied to other environments as well)
    Examples that set-up the SOA-Suite can be found here:
    - http://middlewaremagic.com/weblogic/?p=6040 (discusses considerations when installing the SOA suite)
    - http://middlewaremagic.com/weblogic/?p=6872 (discusses considerations when adding the web-tier to the SOA suite)
    The enterprise deployment guides can help too:
    - SOA Suite: http://download.oracle.com/docs/cd/E21764_01/core.1111/e12036/toc.htm
    - WebCenter: http://download.oracle.com/docs/cd/E21764_01/core.1111/e12037/toc.htm
    These also contain sections on integration with Oracle Identity Management and the Oracle HTTP Server

  • Performance Tuning for BAM 11G

    Hi All
    Can anyone guide me for any documents or any tips realted to performance tuning for BAM 11G on on Linux

    It would help to know if you have any specific issue. There are number of tweaks all they way from DB to Browser.
    Few key things to follow:
    1. Make sure you create index on DO. If there are too much old data in the DO and not useful then periodically delete it. Similar to relational database indexes, defining indexes in Oracle BAM creates and maintains an ordered list of data object elements for fast retrieval.
    2. Ensure that IE setup to do automatic caching. This will help with reducing server round trips.
    3. Tune DB performance. This would typically require DBA. Identify the SQL statements most likely to be causing the waits by looking at
    the drilldown Top SQL Statements Ordered by Wait Time. Use SQL Analyze, EXPLAIN PLAN, or the tkprof utility to tune the queries that were identified.
    Check the Dataobject tables involved in the query for missing indexes.
    4. Use batching (this is on by default for most cases)
    5. Fast network
    6. Use profilers to look at machine load/cpu usage and distribute components on different boxes if needed.
    7. Use better server AND client hardware. BAM dashboard are heavy users of ajax/javascript logic on the client

  • Performance Tuning for Concurrent Reports

    Hi,
    Can you help me with Performance Tuning for Concurrent Reports/Requests ?
    It was running fine but suddenly running slow.
    Request Name : Participation Process: Compensation program

    What is your application release?
    Please see if (Performance Issues With Participation Process: Compensation Workbench [ID 389979.1]) is applicable.
    To enable trace/debug, please see (FAQ: Common Tracing Techniques within the Oracle Applications 11i/R12 [ID 296559.1] -- 5. How does one enable trace for a concurrent program INCLUDING bind variables and waits?).
    Thanks,
    Hussein

  • Need help in developing BADI for IT0001

    Hi All,
    I need help in developing BADI for IT0001.
    On IT0001 create or change, there is need to update IT0017 with following data from IT0001
    -Company Code
    -Cost center
    -Business Area
    -Begin and End Date.
    Other fields from IT0017 need to be derived from Position and update in IT0017.
    Please guide me how I can address this. I do not want to go for dynamic action, as it is not getting evoked during background jobs.
    I am new to BADI development and will appreciate step by step instructions.
    Thanks

    Hi,
         follow the below steps to achive
    Steps:
    1.     Execute Business Add-In(BADI) transaction SE18
    2.     Enter BADI name i.e. HRPAD00INFTY and press the display
            button
    3.     Select menu option Implementation->Create
    4.     Give implementation a name such as Z_HRPAD00INFTY
    5.      You can now make any changes you require to the BADI within this
            implementation, for example choose the Interface tab there are 3 methods avialble
    6.     Double click on the method you want to change, you can now enter
            any code you require.
    7.      Please note to find out what import and export parameters a
            method has got return the original BADI definition
            (i.e. HRPAD00INFTY) and double click on the method name
            for example within HRPAD00INFTY contract is a method
    8.      When changes have been made activate the implementation
    <b>Reward points</b>
    Regards

  • What are the steps doing a performance tuning for pertcular program

    What are the steps doing a performance tuning for pertcular program

    chk this link
    http://www.thespot4sap.com/Articles/SAPABAPPerformanceTuning_PerformanceAnalysisTools.asp
    checkout these links:
    www.sapgenie.com/abap/performance.htm
    www.sap-img.com/abap/ performance-tuning-for-data-selection-statement.htm
    www.thespot4sap.com/Articles/ SAPABAPPerformanceTuning_Introduction.asp
    Message was edited by: Chandrasekhar Jagarlamudi

  • I need help scrolling and highlighting for a vast amount of pics that I'm trying to transfer. I have a macbook pro osx 10.5.8

    I need help scrolling and highlighting for a vast amount of pics that I'm trying to transfer. I have a macbook pro osx 10.5.8

    I need help scrolling and highlighting for a vast amount of pics that I'm trying to transfer. I have a macbook pro osx 10.5.8

  • Performance tuning for siebel CRM application on oracle database

    Hi,
    Please send me the link for Performance tuning for siebel CRM application on oracle database. If there are any white papers please send me the link.
    Thanks,
    Rajesh

    Hi,
    This metalink document is very useful, if you have any other documents or links please inform me.
    Thanks once again
    Rajesh

  • I still need help with the Dictionary for my Nokia...

    I still need help with the Dictionary for my Nokia 6680...
    Here's the error message I get when trying to open dictionary...
    "Dictionary word information missing. Install word database."
    Can someone please provide me a link the where I could download this dictionary for free?
    Thanks!
    DON'T HIT KIDS... THEY HAVE GUNS NOW.

    oops, im sorry, i didnt realised i've already submitted it
    DON'T HIT KIDS... THEY HAVE GUNS NOW.

  • Need help with performance & memory tuning in a data warehousing environment

    Dear All,
    Good Day.
    We had successfully migrated from a 4 node half-rack V2 Exadata to a 2 node quarter rack X4-2 Exadata. However, we are facing some issues with performance only for few loads while others have in fact shown good improvement.
    1. The total memory on the OS is 250GB for each node (two compute nodes for a quarter rack).
    2. Would be grateful if someone could help me with the best equation to calculate the SGA and PGA ( and also in allocation of shared_pool, large_pool etc) or whether Automatic Memory Management is advisable?
    3. We had run exachk report which suggested us to configure huge pages.
    4. When we tried to increase the SGA to more than 30GB the system doesn't allow us to do so. We had however set the PGA to 85GB.
    5. Also, we had observed that some of the queries involving joins and indexes are taking longer time.
    Any advise would be greatly appreciated.
    Warm Regards,
    Vikram.

    Hi Vikram,
    There is no formula about SGA and PGA, but the best practices for OLTP environments is for a give ammount of memory (which cannot be up to 80% of total RAM from server) you should make 80% to SGA and 20% to PGA. For Data Warehouse envs, the values are like 60% SGA and 40% PGA or it can be up to 50%-50%. Also, some docs disencourage you to keep the database in Automatic Memory Management when you are using a big SGA (> 10G).
    As you are using a RAC environment, you should configure Huge Pages. And if the systems are not allowing you to increase memory, just take a look at the semaphore parameters, probably they are set lower values. And for the poor performance queries, we need to see explain plans, table structure and you would also analyze if smart scan is playing the game.
    Regards.

  • Need performance! - Need help with Server Architecture for SSAS on Azure VM

    I would like to build 100% Azure VM base solution. We can install as many as needed.
    I have large amount data in DW. (100GB-1000GB)
    I would like to provide PowerView reports in SharePoints.
    I would like to have report data be as real time as possible. (Min data is updated once in 2 hours)
    These are requirements:
    -SharePoint 2013
    -PowerView
    -SSAS OLAP Cube
    -SQL Server DW&Staging DB (Currently DW&Staging on same server)
    I need help specially what can be done with SSAS to meet requirements? Should be installed to own application server? Possible to install multiple SSAS? SSRS needs own server?
    I appreciate also links to server topology diagrams.
    Kenny_I

    I assume you mean 100GB-1000GB (not 1000TB) right?
    For Sharepoint I would refer to the sizing guide for diagrams and sizing:
    http://technet.microsoft.com/en-us/library/ff758647(v=office.15).aspx
    SSRS (and Power View) will run in the SharePoint farm on a SharePoint app server potentially with other SharePoint services.
    I would definitely put SSAS on a dedicated server for a cube that size. Depending on how well your data compresses, there may not be a VM in Azure with enough RAM to put your model into a Tabular SSAS model. I would prototype it with a subset of data to see
    how well it compresses. You can always use a Multidimensional model as a fallback.
    Depending on how much processing the SSAS model impacts user queries (since it is happening during the day) you could build an SSAS processing server and a separate SSAS query server and run the XMLA Synchronize command to copy the cube incrementally from processing
    to query servers.
    Does that help?
    http://artisconsulting.com/Blogs/GregGalloway

  • Need help in dynamic report for a range of year and period

    Dear all,
    I need help in creating an ALV report with dynamic columns based on the Year and period entered on the selection screen. for example if in the year we enter 2002 and period range from 10 to 12 then we should get the 3 columns display for cost(example) for period 10/2002, 11/2002 and 12/2002.
    Can anyone help me in achieving this dynamically since the user can enter the year also in intervals along with the period and data also needs to be populated in the corresponding columns.
    An example code would be of great help.
    Thanks,
    Amit

    Hi,
    Use field symbols as follows.
    TYPE-POOLS : SLIS.
    TABLES : MARC,T001W.
    DATA : BEGIN OF ITAB OCCURS 0,
           MATNR LIKE MARC-MATNR,
           END OF ITAB.
    DATA : FIELDSTAB TYPE LVC_T_FCAT,
           STAB      TYPE LVC_S_FCAT,
           T_FIELDCAT TYPE SLIS_T_FIELDCAT_ALV,
           S_FIELDCAT TYPE SLIS_FIELDCAT_ALV,
           NEW_LINE TYPE REF TO DATA,
           NEW_TABLE TYPE REF TO DATA,
           INDEX(3) TYPE C,
           STR(70),
           TEXT(6),
           CNT(1),
           TEXT1(16),
           REPID LIKE SY-REPID.
    FIELD-SYMBOLS : <FS> TYPE STANDARD TABLE,
                    <WA> TYPE ANY.
    SELECT-OPTIONS : S_WERKS FOR MARC-WERKS NO INTERVALS,
                     S_MATNR FOR MARC-MATNR NO INTERVALS.
    INITIALIZATION.
      REPID = SY-REPID.
    START-OF-SELECTION.
      SELECT * FROM MARC
               INTO CORRESPONDING FIELDS OF TABLE ITAB
               WHERE MATNR IN S_MATNR
               AND   WERKS IN S_WERKS.
      SORT ITAB BY MATNR.
      DELETE ADJACENT DUPLICATES FROM ITAB COMPARING MATNR.
      STAB-FIELDNAME = 'MATNR'.
      STAB-DATATYPE  = 'CHAR'.
      STAB-INTLEN    = '18'.
      APPEND STAB TO FIELDSTAB.
      CLEAR CNT.
      LOOP AT S_WERKS.
        CLEAR TEXT.
        CNT = CNT + 1.
        CONCATENATE  'EISLO' CNT INTO TEXT.
        STAB-FIELDNAME = TEXT.
        STAB-DATATYPE  = 'CHAR'.
        STAB-INTLEN    = '16'.
        APPEND STAB TO FIELDSTAB.
        CLEAR S_WERKS.
      ENDLOOP.
      CALL METHOD CL_ALV_TABLE_CREATE=>CREATE_DYNAMIC_TABLE
        EXPORTING
          IT_FIELDCATALOG = FIELDSTAB
        IMPORTING
          EP_TABLE        = NEW_TABLE.
      ASSIGN NEW_TABLE->* TO <FS>.
      CREATE DATA NEW_LINE LIKE LINE OF <FS>.
      ASSIGN NEW_LINE->* TO <WA>.
      PERFORM MOVE_DATA.
      CLEAR S_FIELDCAT.
      S_FIELDCAT-FIELDNAME = 'MATNR'.
      S_FIELDCAT-TABNAME = ITAB.
      S_FIELDCAT-SELTEXT_M = 'Part Number'.
      S_FIELDCAT-NO_ZERO = 'X'.
      S_FIELDCAT-DDICTXT   = 'M'.
      APPEND S_FIELDCAT TO T_FIELDCAT.
      CLEAR CNT.
      LOOP AT S_WERKS.
        CLEAR T001W.
        CNT = CNT + 1.
        SELECT SINGLE * FROM T001W WHERE WERKS = S_WERKS-LOW AND SPRAS = SY-LANGU.
        CLEAR TEXT.
        CONCATENATE 'EISLO' CNT INTO TEXT.
        S_FIELDCAT-FIELDNAME = TEXT.
        S_FIELDCAT-SELTEXT_M = T001W-NAME2.
    S_FIELDCAT-NO_ZERO = 'X'.
        S_FIELDCAT-DDICTXT   = 'M'.
        APPEND S_FIELDCAT TO T_FIELDCAT.
        CLEAR S_WERKS.
      ENDLOOP.
      CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
        EXPORTING
          IT_FIELDCAT = T_FIELDCAT[]
        TABLES
          T_OUTTAB    = <FS>.
    *&      Form  MOVE_DATA
          text
    FORM MOVE_DATA.
      LOOP AT ITAB.
        CLEAR STR.
        CONCATENATE ITAB-MATNR ' ' INTO STR SEPARATED BY SPACE.
        LOOP AT S_WERKS.
          CLEAR MARC.
          SELECT SINGLE * FROM MARC WHERE MATNR = ITAB-MATNR AND WERKS = S_WERKS-LOW.
          IF SY-SUBRC EQ 0.
            CLEAR TEXT1.
            TEXT1 = MARC-EISLO.
            CONCATENATE STR TEXT1 INTO STR SEPARATED BY SPACE.
          ELSE.
            CONCATENATE STR '0' INTO STR SEPARATED BY SPACE.
          ENDIF.
        ENDLOOP.
        <WA> = STR.
        APPEND <WA> TO <FS>.
        CLEAR ITAB.
      ENDLOOP.
    ENDFORM.                    "MOVE_DATA
    Reward points if helpful.
    Regards,
    Sankar..

  • Need help in performance

    hallow
    i doing this select and it take more then 10 minutes and i don't now way because
    object_key have just 60 entries ?
    how i can slve this problem?
    Regards
      SELECT * FROM covp APPENDING TABLE *covp
              FOR ALL ENTRIES IN object_key
               WHERE kokrs EQ '1000'
               AND   objnr EQ object_key-objnr
               AND   budat IN so_budat
               AND   stflg EQ space .

    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.

Maybe you are looking for