Nested loop trouble

here's one for all you java gurus:
//import java.util.*;
public class RowsofTen
    //static Scanner console = new Scanner(System.in);
    public static void main (String[] args)
    int i, j;
     for ( i = 11; i <= 40; i++)
       for (j = i; j <= i + 9; j++)
           System.out.print(j + " ");
       System.out.println();
}the output is this:
11 12 13 14 15 16 17 18 19 20
12 13 14 15 16 17 18 19 20 21
13 14 15 16 17 18 19 20 21 22
14 15 16 17 18 19 20 21 22 23
15 16 17 18 19 20 21 22 23 24
16 17 18 19 20 21 22 23 24 25
17 18 19 20 21 22 23 24 25 26
18 19 20 21 22 23 24 25 26 27
19 20 21 22 23 24 25 26 27 28
20 21 22 23 24 25 26 27 28 29
21 22 23 24 25 26 27 28 29 30
22 23 24 25 26 27 28 29 30 31
23 24 25 26 27 28 29 30 31 32
24 25 26 27 28 29 30 31 32 33
25 26 27 28 29 30 31 32 33 34
26 27 28 29 30 31 32 33 34 35
27 28 29 30 31 32 33 34 35 36
28 29 30 31 32 33 34 35 36 37
29 30 31 32 33 34 35 36 37 38
30 31 32 33 34 35 36 37 38 39
31 32 33 34 35 36 37 38 39 40
32 33 34 35 36 37 38 39 40 41
33 34 35 36 37 38 39 40 41 42
34 35 36 37 38 39 40 41 42 43
35 36 37 38 39 40 41 42 43 44
36 37 38 39 40 41 42 43 44 45
37 38 39 40 41 42 43 44 45 46
38 39 40 41 42 43 44 45 46 47
39 40 41 42 43 44 45 46 47 48
40 41 42 43 44 45 46 47 48 49
when i need the output to look like:
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40

first of all, this is a homework problem that i'm having trouble with.
i used your hints and so far i got this:
//import java.util.*;
public class RowsofTen
    //static Scanner console = new Scanner(System.in);
    public static void main (String[] args)
    int i, j;
     for ( i = 1; i <= 3; i++)
       for (j = i * 10 + 1; j <= 40; j++)
           System.out.print(j + " ");
       System.out.println();
}with the output being:
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
31 32 33 34 35 36 37 38 39 40
i'm so close, i just can't figure out how to stop j from increasing after 20 and after 30

Similar Messages

  • Building Tree hierarchy Using nested loops and class cl_gui_column_tree

    Hello gurus,
    I want to create a tree report using custom container and class cl_gui_column_tree. I have read and understood the standard demo report which SAP has provided i.e. SAPCOLUMN_TREE_CONTROL_DEMO. But in this report all the levels nodes are created as constants and hardcoded. I want to create hierarchy using nested loops. For this i took one example of a hierarchy of VBAK-VBELN->VBAP-POSNR Like One sales order has many line items and each line item can have number of line items in billing plan.
    I have done some coding for it.
    FORM build_tree USING node_table TYPE treev_ntab
                                           item_table TYPE zitem_table.              " i created the zitem_table table type of mtreeitm in SE11.
      DATA: node TYPE treev_node,
                 item TYPE mtreeitm.
      node-node_key = root.
      CLEAR node-relatkey.
      CLEAR node-relatship.
      node-hidden = ' '.
      node-disabled = ' '.
      CLEAR node-n_image.
      CLEAR node-exp_image.
      node-isfolder = 'X'.
      node-expander = 'X'.
      APPEND node TO node_table.
      item-node_key = root.
      item-item_name = colm1.
      item-class = cl_gui_column_tree=>item_class_text.
      item-text = 'Root'.
      APPEND item TO item_table.
      item-node_key = root.
      item-item_name = colm2.
      item-class = cl_gui_column_tree=>item_class_text.
      item-text = 'Amount'.
      APPEND item TO item_table.
      LOOP AT it_vbeln INTO wa_vbeln.
        node-node_key = wa_vbeln-vbeln.
        node-relatkey = root.
        node-relatship = cl_gui_column_tree=>relat_last_child.
        node-hidden = ' '.
        node-disabled = ' '.
        CLEAR node-n_image.
        CLEAR node-exp_image.
        node-isfolder = 'X'.
        node-expander = 'X'.
        APPEND node TO node_table.
        item-node_key = wa_vbeln-vbeln.
        item-item_name = colm1.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_vbeln-vbeln.
        APPEND item TO item_table.
        item-node_key = wa_vbeln-vbeln.
        item-item_name = colm2.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_vbeln-netwr.
        APPEND item TO item_table.
        LOOP AT it_posnr INTO wa_posnr.
        node-node_key = wa_posnr-posnr.
        node-relatkey = wa_vbeln-vbeln.
        node-relatship = cl_gui_column_tree=>relat_last_child.
        node-hidden = ' '.
        node-disabled = ' '.
        CLEAR node-n_image.
        CLEAR node-exp_image.
        node-isfolder = ' '.
        node-expander = ' '.
        APPEND node TO node_table.
        item-node_key = wa_posnr-posnr.
        item-item_name = colm1.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_posnr-posnr.
        APPEND item TO item_table.
        item-node_key = wa_posnr-posnr.
        item-item_name = colm2.
        item-class = cl_gui_column_tree=>item_class_text.
        item-text = wa_posnr-netpr.
        APPEND item TO item_table.
        ENDLOOP.
      ENDLOOP.
    ENDFORM.
    Now this program compiles fine and runs till there is only one level. That is root->vbeln. But when i add one more loop of it_posnr it gives me runtime error of message type 'X'. The problem i found was uniqueness of item-item_name as all the sales order have posnr = 0010. What could be done? I tried giving item_name unique hierarchy level using counters just like stufe field in prps eg. 10.10.10, 10.10.20,10.20.10,10.20.20,20.10.10 etc.. etc.. but still i am getting runtime error when i add one more hierarchy using nested loop. Plz guide.
    Edited by: Yayati6260 on Jul 14, 2011 7:25 AM

    Hello all,
    Thanks the issue is solved. The node key was not getting a unique identification as nodekey. I resolved the issue by generating unique identification for each level. Thanks all,
    Regards
    Yayati Ekbote

  • Problem with Nested loop in Fox-Formula

    Dear Experts,
    Let s share the scenario :
    MaterialGroups with following Keys for Example AAAA, BBBB, CCCC..., Materialgroups are selected in the 1st input ready query, which is assigned to DataProvider DP_1 in a  webtemplate.
    every Materialgroup has several Materials, for instance:
    Materialgroup AAAA has following Materials: AAAA10, AAAA11, AAAA12, AAAA13...
    Materials are  selected in a second  input ready Query, which is assigned to a second DataProvider DP_2 in the Same Webtemplate as the query 1.
    Both Materialgroup and Material are based on the same Aggreagtion level and same real time cube.
    I want to copy the input values for every  MaterialGroup ( 1st query, DP_1) only to it s own Materials (2cond Query, DP_2).
    To resolve this Issue i wrote the following Fox Formula code with a nested loop, however it does not work properly. when I m debugging the code, i could release that the second Loop was ignored.but wehn i replace the second loop (nested loop) with a fixed value it s seems to work properly
    DATA MG1 TYPE MATG.<------ MaterialGroup
    DATA MT1 TYPE MAT.<----
    Material
    DATA S1 TYPE STRING.
    DATA S2 TYPE STRING.
    DATA S3 TYPE STRING
    DATA K TYPE F.
    DATA Z TYPE F.
    FOREACH MG1.
    To check Materialgroup in debugger
    S1= MG1.
    BREAK-POINT.
    K = {KEYfIG, #, MG1}.
    BREAK-POINT.
    FOREACH  MT1.   <----- if i set MT1 to a fixed value like AAAA11 then S3 get the wished value namely AAAA
    S2 = MT1.
    BREAK-POINT.
    S3 =  SUBSTR (MT1, 0, 4).  
    BREAK-POINT.
    IF S1 = S3.
    {KEYFIG, MT1, #} = K.
    following Statement is only used To check in debugger if Material has become the same Materialgroup value
    Z = {KEYFIG, MT1, #}.
    BREAK-POINT.
    ENDIF.
    ENDFOR.
    ENDFOR.
    Thakns for any help
    Frank
    Edited by: FRYYYBM on Mar 17, 2011 10:54 PM
    Edited by: FRYYYBM on Mar 17, 2011 11:06 PM

    Hi,
    Please try this way.
    DATA MG1 TYPE MATG.<------ MaterialGroup
    DATA MT1 TYPE MAT.<----
    Material
    DATA S1 TYPE STRING.
    DATA S2 TYPE STRING.
    DATA S3 TYPE STRING
    DATA K TYPE F.
    DATA Z TYPE F.
    FOREACH MT1.
    FOREACH MG1.
    To check Materialgroup in debugger
    S1= MG1.
    BREAK-POINT.
    K = {KEYfIG, #, MG1}.
    BREAK-POINT.
    FOREACH MT1. <----- if i set MT1 to a fixed value like AAAA11 then S3 get the wished value namely AAAA
    S2 = MT1.
    BREAK-POINT.
    S3 = SUBSTR (MT1, 0, 4).
    BREAK-POINT.
    IF S1 = S3.
    {KEYFIG, MT1, #} = K.
    following Statement is only used To check in debugger if Material has become the same Materialgroup value
    Z = {KEYFIG, MT1, #}.
    BREAK-POINT.
    ENDIF.
    ENDFOR.
    ENDFOR.
    ENDFOR.
    Thanks.
    With regards,
    Anand Kumar

  • Creating nested loops

    Hi!
    I would like to list all Combinations of a list A and a list B (each containing 5 integers) in a third list C in order to get 25 combinations. I am intending to use nested loops so that on the first loop the second loop starts and then the result lets say list A + list B are listed in the list C. Is there any other way of doing this with Labview or I am on the right track?
    Best Regards,
    Hamid  

    You can use the polymorphic array math to accomplish this.  Inside of a single for loop, index Array A and add that to the entire Array B in one shot.  At this point, there are numerous ways to take the output.  Probably the simpliest is to reshape the output 2D array into a 1D array.  For better memory allocation, you can preinitialize a 1D array and replace elements in the for loop but in the end it accomplishes the same task.  See attached example (LV7.1.1).  Of course everything is dependant on what you are going to do with this, what operations, when and where the numbers come from.
    Paul
    Paul <--Always Learning!!!
    sense and simplicity.
    Browse my sample VIs?
    Attachments:
    arrayMath.vi ‏33 KB

  • XML nested Loop?

    hi all.
    I´ve just completed a little test for making a tree
    component with custom
    icons / bransch.
    However, i can only get my first branch to show custom
    icons.(links -
    document) I figure I need to make a nested loop to Iterate
    over
    nextSibling?. I tried ALOT, but i guess I´m doing
    something completely
    wrong.
    here is code for my tree so far:
    my_xml = new XML();
    my_xml.ignoreWhite = true;
    my_xml.load("tree.xml");
    my_xml.onLoad = function(){
    myTree.dataProvider = this.firstChild;
    var folders = my_xml.firstChild.firstChild;
    var docs = folders.childNodes;
    for (var i=0; i < docs.length; i++){
    currDoc = docs
    trace(docs);
    var docIcon = currDoc.attributes.pic;
    switch(docIcon){
    case "pdf":
    myTree.setIcon(currDoc, "pdfIcon");
    break;
    case "word":
    myTree.setIcon(currDoc, "wordIcon");
    break;
    case "excel":
    myTree.setIcon(currDoc, "excelIcon");
    break;
    case "ie":
    myTree.setIcon(currDoc, "ieIcon");
    break;
    }//switch
    } //for
    };//onLoad
    And here is the XML I used:
    <node label="» Dokument typer">
    <node label="» links - document">
    <node label="test.url" url="
    http://www." pic="ie" info="test text" />
    <node label="test.doc" url="test.doc" pic="word"
    info="test text" />
    <node label="test.excel" url="test.xls" pic="excel"
    info="test text" />
    <node label="test.pdf" url="test.pdf" pic="pdf"
    info="test text." />
    </node>
    <node label="» Links - document">
    <node label="test URL" url="
    http://www." pic="ie" info="test text."
    />
    <node label="test URL" url="
    http://www." pic="ie" info="test text."
    />
    </node>
    </node>

    Solved it ..works nicely :D
    ty anyways.
    //cleaner
    "cLeAnEr" <[email protected]> skrev i meddelandet
    news:ekm1vc$r8h$[email protected]..
    > hi all.
    >
    > I´ve just completed a little test for making a tree
    component with custom
    > icons / bransch.
    > However, i can only get my first branch to show custom
    icons.(links -
    > document) I figure I need to make a nested loop to
    Iterate over
    > nextSibling?. I tried ALOT, but i guess I´m doing
    something completely
    > wrong.
    >
    >
    > here is code for my tree so far:
    >
    > my_xml = new XML();
    > my_xml.ignoreWhite = true;
    > my_xml.load("tree.xml");
    >
    > my_xml.onLoad = function(){
    > myTree.dataProvider = this.firstChild;
    >
    >
    > var folders = my_xml.firstChild.firstChild;
    > var docs = folders.childNodes;
    >
    > for (var i=0; i < docs.length; i++){
    > currDoc = docs
    > trace(docs);
    >
    > var docIcon = currDoc.attributes.pic;
    >
    > switch(docIcon){
    > case "pdf":
    > myTree.setIcon(currDoc, "pdfIcon");
    > break;
    > case "word":
    > myTree.setIcon(currDoc, "wordIcon");
    > break;
    > case "excel":
    > myTree.setIcon(currDoc, "excelIcon");
    > break;
    > case "ie":
    > myTree.setIcon(currDoc, "ieIcon");
    > break;
    > }//switch
    > } //for
    > };//onLoad
    >
    >
    > And here is the XML I used:
    >
    > <node label="» Dokument typer">
    > <node label="» links - document">
    > <node label="test.url" url="
    http://www." pic="ie" info="test text" />
    > <node label="test.doc" url="test.doc" pic="word"
    info="test text" />
    > <node label="test.excel" url="test.xls" pic="excel"
    info="test text" />
    > <node label="test.pdf" url="test.pdf" pic="pdf"
    info="test text." />
    > </node>
    > <node label="» Links - document">
    > <node label="test URL" url="
    http://www." pic="ie" info="test text."
    />
    > <node label="test URL" url="
    http://www." pic="ie" info="test text."
    />
    > </node>
    > </node>
    >

  • Too many nested loops in execution plan?

    Hi,
    i wonder about execution plan not indicating that access to some tables (for join) is in parallel.
    Please see this example:
    ------------------------ snip ------------------------------------
    drop table test_a1;
    drop table test_a2;
    drop table test_b;
    drop table test_c;
    drop table test_d;
    create table test_a1 (
    x number,
    y number,
    z number);
    create unique index testa1_pk on test_a1 (x);
    create table test_a2 (
    x number,
    y number,
    z number);
    create unique index testa2_pk on test_a2 (x);
    create table test_b (
    x number,
    y number,
    z number);
    create unique index testb_pk on test_b (y);
    create table test_c (
    x number,
    y number,
    z number);
    create unique index testc_pk on test_b (z);
    create table test_d (
    x number,
    y number,
    z number);
    create unique index testd_pk on test_d (y);
    select
    a1.x a1_x,
    a1.y a1_y,
    a1.z a1_z,
    a2.x a2_x,
    a2.y a2_y,
    a2.z a2_z,
    b.x b_x,
    b.y b_y,
    b.z b_z,
    c.x c_x,
    c.y c_y,
    c.z c_z,
    d.x d_x,
    d.y d_y,
    d.z d_z
    from test_a1 a1, test_a2 a2, test_b b, test_c c, test_d d
    where a1.x = 100
    and a2.x = 200
    and b.y = a1.y
    and c.z = b.z
    and d.y = a1.y;
    ------------------------ snap ------------------------------------
    The execution plan goes like this:
    Select Stmt
         nested loops
              nested loops
                   nested loops
                        nested loops
                             table access
                                  index
                                       access predicate
                                            a2.x = 200
                             table access
                                  index
                                       access predicate
                                            a1.x = 100
                        table access
                             index
                                  access predicate
                                       d.y = a1.y
                   table access
                        index
                             access predicate
                                  b.y = a1.y
              table acess
                   index
                        acess predicate
                             c.z = b.z
    Access to tables a1 and a2 is on the same level (in parallel - i guess).
    However, why isn't access to table d and b on the same level?
    Both depend on a1. So no need to execute one after the other (no inter-dependency).
    Maybe i have just wrong expectation to the output of the execution plan(?!)
    - many thanks!
    best regards,
    Frank

    Preservation of identation and spacing is invaluable when it comes to reading an explain plan.
    | Id  | Operation                       | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                |           |     1 |   195 |     2   (0)| 00:00:01 |
    |   1 |  NESTED LOOPS                   |           |     1 |   195 |     2   (0)| 00:00:01 |
    |   2 |   NESTED LOOPS                  |           |     1 |   156 |     0   (0)| 00:00:01 |
    |   3 |    NESTED LOOPS                 |           |     1 |   117 |     0   (0)| 00:00:01 |
    |   4 |     NESTED LOOPS                |           |     1 |    78 |     0   (0)| 00:00:01 |
    |   5 |      TABLE ACCESS BY INDEX ROWID| TEST_A2   |     1 |    39 |     0   (0)| 00:00:01 |
    |*  6 |       INDEX UNIQUE SCAN         | TESTA2_PK |     1 |       |     0   (0)| 00:00:01 |
    |   7 |      TABLE ACCESS BY INDEX ROWID| TEST_A1   |     1 |    39 |     0   (0)| 00:00:01 |
    |*  8 |       INDEX UNIQUE SCAN         | TESTA1_PK |     1 |       |     0   (0)| 00:00:01 |
    |   9 |     TABLE ACCESS BY INDEX ROWID | TEST_D    |    82 |  3198 |     0   (0)| 00:00:01 |
    |* 10 |      INDEX UNIQUE SCAN          | TESTD_PK  |     1 |       |     0   (0)| 00:00:01 |
    |  11 |    TABLE ACCESS BY INDEX ROWID  | TEST_B    |    82 |  3198 |     0   (0)| 00:00:01 |
    |* 12 |     INDEX UNIQUE SCAN           | TESTB_PK  |     1 |       |     0   (0)| 00:00:01 |
    |* 13 |   TABLE ACCESS FULL             | TEST_C    |     1 |    39 |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       6 - access("A2"."X"=200)
       8 - access("A1"."X"=100)
      10 - access("D"."Y"="A1"."Y")
      12 - access("B"."Y"="A1"."Y")
      13 - filter("C"."Z"="B"."Z")
    Access to tables a1 and a2 is on the same level (in parallel - i guess).
    Maybe i have just wrong expectation to the output of the execution plan(?!)You guess wrong, there's nothing parallel going on here.
    Execution plan is a tree of parent-child operations.
    For example, the NESTED LOOP at operation 4 has two children @ 5 and 7.
    Both of these operations- 5 & 7 - have a single child operation.
    The execution tree starts with operation 6, using the TESTA2_PK index to identify rows where A2.X=100.
    From this list of rowids, we go to the table TEST_A2 operation 5.
    The rows from operation five feed into the NESTED LOOP - operation 4.
    For each of these rows, we go to TEST_A1 via the index TEST_A1_PK for rows where A1.X=100.
    This is really a cartesian join because there's no join condition between the two tables.
    etc, etc, etc
    Three things in particular to point out.
    Firstly, that nothing joins to A2. So there will be a cartesian product - i.e. for every row in the result set between the joined tables A1, B, C and D, these will be multiplied by the number of rows returned by the the A2 rowsource.
    Secondly, when everything has got one or zero rows (or the optimizer thinks that it's one or zero rows), you can get very different plans from when there are known/thought to be more rows.
    Both depend on a1. So no need to execute one after the other (no inter-dependency).Thirdly, in terms of isolated join operations (ignoring A2 and C for the moment), A1 cannot join to B and D at the same time, you can either join A1 to B and then join the result of that to D, or join A1 to D then B, which is what you've got in your plan (well, actually we have A2 joined to A1 then the result of that joined to D and then the result of that to B).
    Edited by: Dom Brooks on Jul 6, 2011 4:07 PM
    Corrected typo

  • Why optimizer prefers nested loop over hash join?

    What do I look for if I want to find out why the server prefers a nested loop over hash join?
    The server is 10.2.0.4.0.
    The query is:
    SELECT p.*
        FROM t1 p, t2 d
        WHERE d.emplid = p.id_psoft
          AND p.flag_processed = 'N'
          AND p.desc_pool = :b1
          AND NOT d.name LIKE '%DUPLICATE%'
          AND ROWNUM < 2tkprof output is:
    Production
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.01       0.00          0          0          4           0
    Execute      1      0.00       0.01          0          4          0           0
    Fetch        1    228.83     223.48          0    4264533          0           1
    total        3    228.84     223.50          0    4264537          4           1
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 108  (SANJEEV)
    Rows     Row Source Operation
          1  COUNT STOPKEY (cr=4264533 pr=0 pw=0 time=223484076 us)
          1   NESTED LOOPS  (cr=4264533 pr=0 pw=0 time=223484031 us)
      10401    TABLE ACCESS FULL T1 (cr=192 pr=0 pw=0 time=228969 us)
          1    TABLE ACCESS FULL T2 (cr=4264341 pr=0 pw=0 time=223182508 us)Development
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.01       0.00          0          0          0           0
    Execute      1      0.00       0.01          0          4          0           0
    Fetch        1      0.05       0.03          0        512          0           1
    total        3      0.06       0.06          0        516          0           1
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 113  (SANJEEV)
    Rows     Row Source Operation
          1  COUNT STOPKEY (cr=512 pr=0 pw=0 time=38876 us)
          1   HASH JOIN  (cr=512 pr=0 pw=0 time=38846 us)
         51    TABLE ACCESS FULL T2 (cr=492 pr=0 pw=0 time=30230 us)
        861    TABLE ACCESS FULL T1 (cr=20 pr=0 pw=0 time=2746 us)

    sanjeevchauhan wrote:
    What do I look for if I want to find out why the server prefers a nested loop over hash join?
    The server is 10.2.0.4.0.
    The query is:
    SELECT p.*
    FROM t1 p, t2 d
    WHERE d.emplid = p.id_psoft
    AND p.flag_processed = 'N'
    AND p.desc_pool = :b1
    AND NOT d.name LIKE '%DUPLICATE%'
    AND ROWNUM < 2
    You've got already some suggestions, but the most straightforward way is to run the unhinted statement in both environments and then force the join and access methods you would like to see using hints, in your case probably "USE_HASH(P D)" in your production environment and "FULL(P) FULL(D) USE_NL(P D)" in your development environment should be sufficient to see the costs and estimates returned by the optimizer when using the alternate access and join patterns.
    This give you a first indication why the optimizer thinks that the chosen access path seems to be cheaper than the obviously less efficient plan selected in production.
    As already mentioned by Hemant using bind variables complicates things a bit since EXPLAIN PLAN is not reliable due to bind variable peeking performed when executing the statement, but not when explaining.
    Since you're already on 10g you can get the actual execution plan used for all four variants using DBMS_XPLAN.DISPLAY_CURSOR which tells you more than the TKPROF output in the "Row Source Operation" section regarding the estimates and costs assigned.
    Of course the result of your whole exercise might be highly dependent on the actual bind variable value used.
    By the way, your statement is questionable in principle since you're querying for the first row of an indeterministic result set. It's not deterministic since you've defined no particular order so depending on the way Oracle executes the statement and the physical storage of your data this query might return different results on different runs.
    This is either an indication of a bad design (If the query is supposed to return exactly one row then you don't need the ROWNUM restriction) or an incorrect attempt of a Top 1 query which requires you to specify somehow an order, either by adding a ORDER BY to the statement and wrapping it into an inline view, or e.g. using some analytic functions that allow you specify a RANK by a defined ORDER.
    This is an example of how a deterministic Top N query could look like:
    SELECT
    FROM
    SELECT p.*
        FROM t1 p, t2 d
        WHERE d.emplid = p.id_psoft
          AND p.flag_processed = 'N'
          AND p.desc_pool = :b1
          AND NOT d.name LIKE '%DUPLICATE%'
    ORDER BY <order_criteria>
    WHERE ROWNUM <= 1;Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Nested loop vs Hash Join

    Hi,
    Both the querys are returning same results, but in my first query hash join and second query nested loop . How ? PLs explain
    select *
    from emp a,dept b
    where a.deptno=b.deptno and b.deptno>20;
    6 rows
    Plan hash value: 4102772462
    | Id  | Operation                    | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT             |         |     6 |   348 |     6  (17)| 00:00:01 |
    |*  1 |  HASH JOIN                   |         |     6 |   348 |     6  (17)| 00:00:01 |
    |   2 |   TABLE ACCESS BY INDEX ROWID| DEPT    |     3 |    60 |     2   (0)| 00:00:01 |
    |*  3 |    INDEX RANGE SCAN          | PK_DEPT |     3 |       |     1   (0)| 00:00:01 |
    |*  4 |   TABLE ACCESS FULL          | EMP     |     7 |   266 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - access("A"."DEPTNO"="B"."DEPTNO")
       3 - access("B"."DEPTNO">20)
       4 - filter("A"."DEPTNO">20)
    select *
    from emp a,dept b
    where a.deptno=b.deptno and b.deptno=30;  
    6 rows
    Plan hash value: 568005898
    | Id  | Operation                    | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT             |         |     5 |   290 |     4   (0)| 00:00:01 |
    |   1 |  NESTED LOOPS                |         |     5 |   290 |     4   (0)| 00:00:01 |
    |   2 |   TABLE ACCESS BY INDEX ROWID| DEPT    |     1 |    20 |     1   (0)| 00:00:01 |
    |*  3 |    INDEX UNIQUE SCAN         | PK_DEPT |     1 |       |     0   (0)| 00:00:01 |
    |*  4 |   TABLE ACCESS FULL          | EMP     |     5 |   190 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       3 - access("B"."DEPTNO"=30)
       4 - filter("A"."DEPTNO"=30)

    Hi,
    Unless specifically requested, Oracle picks the best execution plan based on estimates of table sizes, column selectivity and many other variables. Even though Oracle does its best to have the estimates as accurate as possible, they are frequently different, and in some cases quite different, from the actual values.
    In the first query, Oracle estimated that the predicate “ b.deptno>20” would limit the number of records to 6, and based on that it decided the use Hash Join.
    In the second query, Oracle estimated that the predicate “b.deptno=30” would limit the number of records to 5, and based on that it decided the use Nested Loops Join.
    The fact that the actual number of records is the same is irrelevant because Oracle used the estimate, rather the actual number of records to pick the best plan.
    HTH,
    Iordan
    Iotzov

  • Hash join vs nested loop

    DECLARE @tableA table (Productid varchar(20),Product varchar(20),RateID int)
    insert into @tableA values('1','Mobile',2);
    insert into @tableA values('2','Chargers',4);
    insert into @tableA values('3','Stand',6);
    insert into @tableA values('4','Adapter',8);
    insert into @tableA values('5','Cover',10);
    insert into @tableA values('6','Protector',12);
    --SELECT * FROM @tableA
    DECLARE @tableB table (id varchar(20),RateID int,Rate int)
    insert into @tableB values('1',2,200);
    insert into @tableB values('2',4,40);
    insert into @tableB values('3',6,60);
    insert into @tableB values('4',8,80);
    insert into @tableB values('5',10,10);
    insert into @tableB values('6',12,15);
    --SELECT * FROM @tableB
    SELECT Product,Rate
    FROM @tableA a
    JOIN @tableB b ON a.RateID = b.RateID
    Above is the sample query, where in execution plan it shows the Hash Match (inner Join). Now how do I change it to Nested Loop with out changing the query? help plz

    Is Hash Match(inner join) or Nested loop is better to have in the query?
    That depends on the size of the tables, available indexes etc. The optimizer will (hopefully) make the best choice.
    Above is the sample query, where in execution plan it shows the Hash Match (inner Join). Now how do I change it to Nested Loop with out changing the query?
    The answer that you should leave that to the optimizer in most cases.
    I see that the logical read for nested loop is higher than Hash Match.
    But Hash Match tends to need more CPU. The best way to two compare two queries or plans is wallclock time.
    On a big tables, how do we reduce the logical read? 
    Make sure that there are usable indexes.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • HASH JOIN or NESTED LOOP

    I've been asked to check if HASH JOIN is more suitable than NESTED LOOP(which CBO chose by default) for the following query.
    SELECT CM_DETAILS.TASK_ID FROM GEN_TYPE, CM_DETAILS WHERE ( ( ( ( ( CM_DETAILS.STAT_CODE < 8 ) AND ( GEN_TYPE.TASK_ID = CM_DETAILS.TASK_ID ) ) AND ( GEN_TYPE.DEST_LOCN_ID = 5 ) ) AND ( GEN_TYPE.COM_ID = 7 ) ) AND ( ( ( CM_DETAILS.CASE_NO = 1 ) OR ( CM_DETAILS.CASE_NO = 3 ) ) OR ( CM_DETAILS.CASE_NO = 9 ) ) )
    Both GEN_TYPE and CM_DETAILS tables have over 330,000 rows.
    Version: 10g R2
    Any thoughts?

    As gintsp gave you very nice tip but there is initialization parameter "     OPTIMIZER_INDEX_COST_ADJ" which cause what path to be chose for CBO,but usually expert says for changing init paramter setting should be at last resort.
    It has default value of 100 which indicates to the CBO that indexed access is 100% as costly (i.e., equally costly) as FULL table scan access.
    SQL> column plan_plus_exp format a100
    SQL> set linesize 1000
    SQL> SET AUTOTRACE TRACEONLY
    SQL> SELECT e.ename,d.dname
      2    FROM emp e,dept d
      3   WHERE e.deptno=d.deptno
      4  /
    14 rows selected.
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=7 Card=10 Bytes=320)
       1    0   HASH JOIN (Cost=7 Card=10 Bytes=320)
       2    1     TABLE ACCESS (FULL) OF 'DEPT' (TABLE) (Cost=3 Card=5 Bytes=90)
       3    1     TABLE ACCESS (FULL) OF 'EMP' (TABLE) (Cost=3 Card=14 Bytes=196)
    Statistics
            672  recursive calls
              0  db block gets
            151  consistent gets
             27  physical reads
              0  redo size
            793  bytes sent via SQL*Net to client
            508  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
             15  sorts (memory)
              0  sorts (disk)
             14  rows processed
    SQL> /
    14 rows selected.
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=7 Card=10 Bytes=320)
       1    0   HASH JOIN (Cost=7 Card=10 Bytes=320)
       2    1     TABLE ACCESS (FULL) OF 'DEPT' (TABLE) (Cost=3 Card=5 Bytes=90)
       3    1     TABLE ACCESS (FULL) OF 'EMP' (TABLE) (Cost=3 Card=14 Bytes=196)
    Statistics
              0  recursive calls
              0  db block gets
             15  consistent gets
              0  physical reads
              0  redo size
            793  bytes sent via SQL*Net to client
            508  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
             14  rows processed
    SQL> SHOW PARAMETER optimizer
    NAME                                 TYPE                             VALUE
    optimizer_dynamic_sampling           integer                          2
    optimizer_features_enable            string                           10.1.0
    optimizer_index_caching              integer                          0
    optimizer_index_cost_adj             integer                          100<--------
    optimizer_mode                       string                           ALL_ROWS
    SQL> ALTER SESSION SET optimizer_index_cost_adj=35
      2  /
    Session altered.
    SQL> SELECT e.ename,d.dname
      2    FROM emp e,dept d
      3   WHERE e.deptno=d.deptno
      4  /
    14 rows selected.
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=5 Card=10 Bytes=320)
       1    0   MERGE JOIN (Cost=5 Card=10 Bytes=320)
       2    1     TABLE ACCESS (BY INDEX ROWID) OF 'DEPT' (TABLE) (Cost=1 Card=5 Bytes=90)
       3    2       INDEX (FULL SCAN) OF 'DEPT_PRIMARY_KEY' (INDEX (UNIQUE)) (Cost=1 Card=5)
       4    1     SORT (JOIN) (Cost=4 Card=14 Bytes=196)
       5    4       TABLE ACCESS (FULL) OF 'EMP' (TABLE) (Cost=3 Card=14 Bytes=196)
    Statistics
              1  recursive calls
              0  db block gets
             11  consistent gets
              1  physical reads
              0  redo size
            733  bytes sent via SQL*Net to client
            508  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
             14  rows processed
    SQL> /
    14 rows selected.
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=5 Card=10 Bytes=320)
       1    0   MERGE JOIN (Cost=5 Card=10 Bytes=320)
       2    1     TABLE ACCESS (BY INDEX ROWID) OF 'DEPT' (TABLE) (Cost=1 Card=5 Bytes=90)
       3    2       INDEX (FULL SCAN) OF 'DEPT_PRIMARY_KEY' (INDEX (UNIQUE)) (Cost=1 Card=5)
       4    1     SORT (JOIN) (Cost=4 Card=14 Bytes=196)
       5    4       TABLE ACCESS (FULL) OF 'EMP' (TABLE) (Cost=3 Card=14 Bytes=196)
    Statistics
              0  recursive calls
              0  db block gets
             11  consistent gets
              0  physical reads
              0  redo size
            733  bytes sent via SQL*Net to client
            508  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
             14  rows processedKhurram

  • Oracle 11g - Nested loops on outer joins

    Hello,
    I have a select query that was working with no problems. The results are used to insert data into a temp table.
    Recently, it would not complete executing. The explain plan shows a cartesian. But, there could be problems with using nested loops on the outer join. Interestingly, when I copy production code and rename the temp table and rename the view, it works.
    Can someone take a look at the code and help. Maybe offer a suggestion on tuning too? Thanks.
    CREATE TABLE "CT"
    ( "TN" VARCHAR2(30) NOT NULL ENABLE,
    "COL_NAME" VARCHAR2(30) NOT NULL ENABLE,
    "CDE" VARCHAR2(5) NOT NULL ENABLE,
    "CDE_DESC" VARCHAR2(80) NOT NULL ENABLE,
    "CDE_STAT" CHAR(1));
    insert into CT (TN, COL_NAME, CDE, CDE_DESC, CDE_STAT)
    values ('INDSD', 'STCD', 'U', 'RF', 'A');
    insert into CT (TN, COL_NAME, CDE, CDE_DESC, CDE_STAT)
    values ('AT', 'TCD', '001', 'RL', 'A');
    insert into CT (TN, COL_NAME, CDE, CDE_DESC, CDE_STAT)
    values ('AT', 'TCD', '033', 'PFR', 'A');
    CREATE TABLE "IPP"
    ( "IND_ID" NUMBER(9,0) NOT NULL ENABLE,
    "PLCD" VARCHAR2(5) NOT NULL ENABLE,
    "CBCD" VARCHAR2(5));
    insert into IPP (IND_ID, PLCD, CBCD)
    values (2007, 'AS', '04');
    insert into IPP (IND_ID, PLCD, CBCD)
    values (797098, 'AS', '34');
    insert into IPP (IND_ID, PLCD, CBCD)
    values (797191, 'AS','04');
    CREATE TABLE "INDS"
    ( "OPCD" VARCHAR2(5) NOT NULL ENABLE,
    "IND_ID" NUMBER(9,0) NOT NULL ENABLE,
    "IND_CID" NUMBER(*,0),
    "GFLG" VARCHAR2(1),
    "HHID" NUMBER(9,0),
    "DOB" DATE,
    "DOB_FLAG" VARCHAR2(1),
    "VCD" VARCHAR2(5),
    "VTDTE" DATE,
    "VPPCD" VARCHAR2(4),
    "VRCDTE" DATE NOT NULL ENABLE,
    "VDSID" NUMBER(9,0),
    "VTRANSID" NUMBER(12,0),
    "VOWNCD" VARCHAR2(5),
    "RCDTE" DATE,
    "LRDTE" DATE
    insert into INDS (OPCD, IND_ID, IND_CID, GFLG, HHID, DOB, DOB_FLAG, VCD, VTDTE, VPPCD, VRCDTE, VDSID, VTRANSID, VOWNCD, RCDTE, LRDTE)
    values ('USST', 2007, 114522319, '', 304087673, to_date('01-01-1980', 'dd-mm-yyyy'), 'F', '2', to_date('06-04-2011 09:21:37', 'dd-mm-yyyy hh24:mi:ss'), '', to_date('06-04-2011 09:21:37', 'dd-mm-yyyy hh24:mi:ss'), 1500016, null, 'USST', to_date('06-04-2011 09:21:37', 'dd-mm-yyyy hh24:mi:ss'), to_date('18-07-2012 21:52:53', 'dd-mm-yyyy hh24:mi:ss'));
    insert into INDS (OPCD, IND_ID, IND_CID, GFLG, HHID, DOB, DOB_FLAG, VCD, VTDTE, VPPCD, VRCDTE, VDSID, VTRANSID, VOWNCD, RCDTE, LRDTE)
    values ('USST', 304087678, 115242519, '', 304087678, to_date('01-01-1984', 'dd-mm-yyyy'), 'F', '2', to_date('06-04-2011 09:21:39', 'dd-mm-yyyy hh24:mi:ss'), '', to_date('06-04-2011 09:21:39', 'dd-mm-yyyy hh24:mi:ss'), 1500016, null, 'USST', to_date('06-04-2011 09:21:39', 'dd-mm-yyyy hh24:mi:ss'), to_date('18-07-2012 21:52:53', 'dd-mm-yyyy hh24:mi:ss'));
    CREATE TABLE "INDS_TYPE"
    ( "IND_ID" NUMBER(9,0) NOT NULL ENABLE,
    "STCD" VARCHAR2(5) NOT NULL ENABLE);
    insert into INDS_type (IND_ID, STCD)
    values (2007, 'U');
    insert into INDS_type (IND_ID, STCD)
    values (313250322, 'U');
    insert into INDS_type (IND_ID, STCD)
    values (480058122, 'U');
    CREATE TABLE "PLOP"
    ( "OPCD" VARCHAR2(5) NOT NULL ENABLE,
    "PLCD" VARCHAR2(5) NOT NULL ENABLE,
    "PPLF" VARCHAR2(1));
    insert into PLOP (OPCD, PLCD, PPLF)
    values ('USST', 'SP', 'Y');
    insert into PLOP (OPCD, PLCD, PPLF)
    values ('PMUSA', 'ST', '');
    insert into PLOP (OPCD, PLCD, PPLF)
    values ('USST', 'RC', '');
    CREATE TABLE "IND_T"
    ( "OPCD" VARCHAR2(5) NOT NULL ENABLE,
    "CID" NUMBER(9,0) NOT NULL ENABLE,
    "CBCD" VARCHAR2(5),
    "PF" VARCHAR2(1) NOT NULL ENABLE,
    "DOB" DATE,
    "VCD" VARCHAR2(5),
    "VOCD" VARCHAR2(5),
    "IND_CID" NUMBER,
    "RCDTE" DATE NOT NULL ENABLE
    insert into IND_T (OPCD, CID, CBCD,PF, DOB, VCD, VOCD, IND_CID, RCDTE)
    values ('JMC', 2007, '04', 'F',to_date('11-10-1933', 'dd-mm-yyyy'), '2', 'PMUSA', 363004880, to_date('30-09-2009 04:31:34', 'dd-mm-yyyy hh24:mi:ss'));
    insert into IND_T (OPCD, CID, CBCD,PF, DOB, VCD, VOCD, IND_CID, RCDTE)
    values ('JMC', 2008, '04', 'N',to_date('01-01-1980', 'dd-mm-yyyy'), '2', 'PMUSA', 712606335, to_date('05-04-2013 19:36:05', 'dd-mm-yyyy hh24:mi:ss'));
    CREATE TABLE "IC"
    ( "CID" NUMBER(9,0) NOT NULL ENABLE,
    "CF" CHAR(1));
    insert into IC (CID, CF)
    values (2007, 'N');
    insert into IC (CID, CF)
    values (100, 'N');
    insert into IC (CID, CF)
    values (200, 'N');
    CREATE OR REPLACE FORCE VIEW "INDSS_V" ("OPCD", "IND_ID", "IND_CID", "GFLG", "HHID", "DOB", "DOB_FLAG", "VCD", "VTDTE", "VPPCD", "VRCDTE", "VDSID", "VTRANSID", "VOWNCD", "RCDTE", "LRDTE") AS
    SELECT DISTINCT a.OPCD, a.IND_ID, a.IND_CID, a.GFLG, a.HHID,
    a.DOB, a.DOB_flag, a.VCD, a.VTDTE,
    a.VPPCD, a.VRCDTE, a.VDSID, a.VTRANSID,
    a.VOWNCD, a.RCDTE, a.LRDTE
    FROM INDS a, INDS_type b
    WHERE a.IND_ID = b.IND_ID
    AND b.STCD in (select CDE
    from CT --database link
    where TN = 'INDSD'
    and COL_NAME = 'STCD'
    and CDE_STAT = 'A') ;
    --insert /*+ parallel(IND_T,2) */ into IND_T
    select /*+ parallel(a,4) */
    a.OPCD as OPCD
    , a.IND_ID as CID
    , b.CBCD as CBCD
    , NULL as BFCD
    , 'N' as PF
    , a.DOB as DOB
    , a.VCD as VCD
    , a.VOWNCD as VOCD
    , a.IND_CID as IND_CID
    , a.RCDTE as RCDTE
    from INDSS_V a
    , (select /*+ parallel(IPP,4) */ * from IPP IPP , PLOP PLO
    where plo.PLCD = ipp.PLCD
    and PPLF='Y') b
    , IC c
    where a.IND_ID = b.IND_ID (+)
    and a.OPCD = b.OPCD (+)
    and a.IND_ID = c.CID
    and c.CF = 'N';

    Please consult
    HOW TO: Post a SQL statement tuning request - template posting
    Also format your code and post it using the [ code ] and [ /code ] tags. (Leave out the extra space after [ and before ])
    Sybrand Bakker
    Senior Oracle DBA
    Edited by: sybrand_b on 10-apr-2013 17:57

  • Several nested loop at the same level in an execution plan

    Hi, I am using 11gR2, and I've seen a execution plan in the trace of my SQL query (also shown in pl/sql explain plan) with 4 nested loops all at the same level, what does this mean?
    i.e.
    - SELECT STATEMENT, GOAL = FIRST_ROWS
    + NESTED LOOPS
    + NESTED LOOPS
    + NESTED LOOPS
    + NESTED LOOPS
    each NESTED LOOP can be expanded to 2 further actions, which make sense to me. e.g.
    + NESTED LOOPS
    + TABLE ACCESS BY INDEX ROWID
    + TABLE ACCESS BY INDEX ROWID
    THANKS
    Ye

    >
    why there are 4 Nested Loops
    what is the final result set for the SELECT statement come from (any one of the 4)
    the query run so slow in 11R2
    >
    So far you are the only one who knows what the query and execution plan are because you haven't posted them
    >
    Then you need to post the query, tell us what indexes are on the join columns and post the complete plan.
    >
    We can't even begin to explain why Oracle might have chosen the plan it did if we can't see the query and plan you want explained.
    And if we only see the plan we might be able to tell you what Oracle is doing but without knowing what indexes might be on the join columns and the filter criteria columns we can't tell you why Oracle chose the plan it chose.
    And the excerpt of the plan you did provide is incomplete. You removed the indenting possibly because you did not enclose it in 'code' tags (see the FAQ).
    >
    - SELECT STATEMENT, GOAL = FIRST_ROWS
    + NESTED LOOPS
    + NESTED LOOPS
    + NESTED LOOPS
    + NESTED LOOPS
    >
    There can't be four nested loops like that at the top level since the top level will be combining the result sets from it's children. A nested loop will have two children; like the last part you showed:
    >
    + NESTED LOOPS
    + TABLE ACCESS BY INDEX ROWID
    + TABLE ACCESS BY INDEX ROWID
    >
    The two 'TABLE ACCESS ...' will be indented on a normal plan.
    Without the query and plan there isn't much we can tell you.

  • Explain Plan shows Nested Loops, Is it good or bad?

    Hi All,
    I have a doubt in the explain plan, I would like to know if the Nested Loops , will it degrade the query performance?
    Note: I have pasted only few output that I had taken from the expalin plan.
    Do let me know if there is any article I could read to get clear understanding about the same.
    17 NESTED LOOPS ANTI Cost: 125 Bytes: 186 Cardinality: 1                                                                  
    15 NESTED LOOPS ANTI Cost: 124 Bytes: 166 Cardinality: 1                                                             
    12 NESTED LOOPS Cost: 122 Bytes: 140 Cardinality: 1                                                        
         9 NESTED LOOPS Cost: 121 Bytes: 117 Cardinality: 1           
    Thanks

    Hi,
    there is absolutely nothing wrong about nested loops (NL). It's a very efficient way of combining data from two rowsources. It works pretty much like a regular loop: it takes all rows from one rowsource (the "outer" one) and for each of them it looks up a row matching the join condition in the other rowsource (the "inner" one).
    Note that there are not so many alternatives in Oracle: there are only 3 ways to join data in Oracle, and one of them is used in rather special circumstances (merge join). So normally the choice is between a NL and a hash join. Hash join (HJ) takes the smaller dataset and builds an in-memory lookup table using a hash function on join column(s). Then it goes through the other dataset and as it goes, it applies the hashing function to join column(s) and picks the matching rows from the smaller dataset.
    Actually, hash joins and nested loops are not all that different. The basic mechanism is same: you go through one datasource and as you go, you pick matching rows from the other and do the join. The main difference is that a HJ requires some preparation work (it costs resources to build the in-memory table) and thus HJ are typically associated with less-selective queries and full table scans.
    In your particular case it's nor possible to tell whether or not NL is in order based on just a few rows from the explain plan. We need to know the structure of your tables (the DDL), what kind of data they hold (optimizer stats) and what query you are running to be able to tell.
    Best regards,
    Nikolay

  • Slightly ot: - how to this without a nested loop?

    HI,
    At the mo I have the following:
    A db tbl of customers. I loop through each one, then within
    the loop I then open up a tbl checking their last order. if that
    meets certain criteria then I set a condition to true.
    I then close the order tbl, then continue the customer
    loop./.. and so on....
    However as the customer tbl is growing quite large, this is
    obviously not the greatest way of doing it.
    If I try and do a join on the two tables to check the
    critieria of the orders, it checks all the orders for that
    customer, not just the last one..
    I need my tbl join to only include the very last order for
    that particular customer.
    In my current nested loop I get this by checking for the
    order_date ORDER BY DESC
    Any ideas how I can do this?

    In your SQL, if you keep the ORDER BY DESC but in your SELECT
    use SELECT TOP
    1 (Id) - followed by your column names. This is presuming you
    have an
    auto-incrementing Id.
    "jamesy" <[email protected]> wrote in message
    news:ea7fo4$s0p$[email protected]..
    > HI,
    > At the mo I have the following:
    > A db tbl of customers. I loop through each one, then
    within the loop I
    > then
    > open up a tbl checking their last order. if that meets
    certain criteria
    > then I
    > set a condition to true.
    > I then close the order tbl, then continue the customer
    loop./.. and so
    > on....
    >
    > However as the customer tbl is growing quite large, this
    is obviously not
    > the
    > greatest way of doing it.
    >
    > If I try and do a join on the two tables to check the
    critieria of the
    > orders,
    > it checks all the orders for that customer, not just the
    last one..
    >
    > I need my tbl join to only include the very last order
    for that particular
    > customer.
    >
    > In my current nested loop I get this by checking for the
    order_date ORDER
    > BY
    > DESC
    >
    >
    > Any ideas how I can do this?
    >
    >
    >

  • Hi how to avoid nested loops in this program to improve the performence

    Hi all
    How to avoide the nested loops in this programing what is the replacement for the nested loops in this program coding......
    LOOP AT itb_ekpo.
        READ TABLE itb_marc WITH KEY
           matnr = itb_ekpo-matnr
           werks = itb_ekpo-werks BINARY SEARCH.
        CHECK sy-subrc = 0.
    FAE 26446 fin remplacement
        itb_pca-ebeln = itb_ekpo-ebeln.
        itb_pca-ebelp = itb_ekpo-ebelp.
      itb_pca-lifnr = itb_ekko-lifnr.   "-FAE26446
        itb_pca-lifnr = itb_ekpo-lifnr.                         "+FAE26446
        itb_pca-ekgrp = itb_ekpo-ekgrp.                         "+FAE26446
        itb_pca-dispo = itb_ekpo-dispo.                         "+FAE26446
        itb_pca-matnr = itb_ekpo-matnr.
        itb_pca-werks = itb_ekpo-werks.
      Recherche du libellé article
        READ TABLE itb_makt
                   WITH KEY matnr = itb_ekpo-matnr
                            spras = text-fra
                   BINARY SEARCH.
        IF sy-subrc = 0.
          itb_pca-maktx = itb_makt-maktx.
        ELSE.
          READ TABLE itb_makt
                    WITH KEY matnr = itb_ekpo-matnr
                             spras = text-ang
                    BINARY SEARCH.
          IF sy-subrc = 0.
            itb_pca-maktx = itb_makt-maktx.
          ENDIF.
        ENDIF.
        IF NOT itb_ekpo-bpumn IS INITIAL.
          itb_pca-menge = itb_ekpo-menge * itb_ekpo-bpumz /
                                           itb_ekpo-bpumn.
        ENDIF.
      Sélect° ds la table EKES des dates de livraisons et des qtés
      en transit
        CLEAR w_temoin_ar.
        CLEAR w_etens.
        LOOP AT itb_ekes
                FROM w_index_ekes.
          IF  itb_ekes-ebeln = itb_ekpo-ebeln
          AND itb_ekes-ebelp = itb_ekpo-ebelp.
            IF itb_ekes-ebtyp = text-arn.
              itb_pca-eindt = itb_ekes-eindt.
              w_temoin_ar = 'X'.
            ELSE.
            Si c'est une qté en transit alors on recupere
            la quantité et la date.
              IF itb_ekes-dabmg < itb_ekes-menge.
                itb_pca-qtran = itb_pca-qtran + itb_ekes-menge -
                                itb_ekes-dabmg.
              ENDIF.
              IF itb_ekes-etens > w_etens.
                w_etens = itb_ekes-etens.
                itb_pca-dtran = itb_ekes-eindt.
              ENDIF.
            ENDIF.
          ELSEIF itb_ekes-ebeln > itb_ekpo-ebeln
          OR ( itb_ekes-ebeln = itb_ekpo-ebeln
          AND itb_ekes-ebelp > itb_ekpo-ebelp ).
            w_index_ekes = sy-tabix.
            EXIT.
          ENDIF.
        ENDLOOP.
      S'il n'y a pas d'AR alors récupérat° de la date livraison dans EKET.
        LOOP AT itb_eket
                FROM w_index_eket.
          IF  itb_eket-ebeln = itb_ekpo-ebeln
          AND itb_eket-ebelp = itb_ekpo-ebelp.
            IF w_temoin_ar IS INITIAL.
              itb_pca-eindt = itb_eket-eindt.
            ENDIF.
            itb_pca-slfdt = itb_eket-slfdt.
          Calcul du portefeuille fournisseur à partir de la
          qté commandée et la qté reçue
            itb_pca-attdu = itb_pca-attdu + itb_eket-menge -
                            itb_eket-wemng.
          Calcul du montant du poste
            itb_pca-netpr = itb_ekpo-netpr * itb_pca-attdu.
            IF itb_ekpo-peinh NE 0.
              itb_pca-netpr = itb_pca-netpr / itb_ekpo-peinh.
            ENDIF.
          Calcul quantité réceptionnée.
            itb_pca-wemng = itb_pca-wemng + itb_eket-wemng.
          Calcul du retard en nombre de jours calendaires
          Le calcul du retard  ne doit pas prendre en compte
          le jour de livraison
            ADD 1 TO itb_eket-eindt.
            IF NOT itb_pca-attdu  IS INITIAL
            AND    itb_eket-eindt LT sy-datum.
            Calcul du retard en nombre de jours ouvrés
              CLEAR w_retard.
              CALL FUNCTION 'Z_00_BC_WORKDAYS_PER_PERIOD'
                   EXPORTING
                        date_deb = itb_eket-eindt
                        date_fin = sy-datum
                   IMPORTING
                        jours    = w_retard.
              itb_pca-rtard = itb_pca-rtard + w_retard .
            ENDIF.
          ELSEIF itb_eket-ebeln > itb_ekpo-ebeln
          OR (   itb_eket-ebeln = itb_ekpo-ebeln
          AND    itb_eket-ebelp > itb_ekpo-ebelp ).
            w_index_eket = sy-tabix.
            EXIT.
          ENDIF.
        ENDLOOP.
      Recherche de la derniere date de livraison.
        LOOP AT itb_mseg
                FROM w_index_mseg.
          IF  itb_mseg-ebeln = itb_ekpo-ebeln
          AND itb_mseg-ebelp = itb_ekpo-ebelp.
            READ TABLE itb_mkpf
                       WITH KEY mblnr = itb_mseg-mblnr
                                mjahr = itb_mseg-mjahr
                       BINARY SEARCH.
            IF sy-subrc = 0.
              IF itb_mkpf-bldat > itb_pca-bldat.
                itb_pca-bldat = itb_mkpf-bldat.
              ENDIF.
            ENDIF.
          ELSEIF itb_mseg-ebeln > itb_ekpo-ebeln
          OR (   itb_mseg-ebeln = itb_ekpo-ebeln
          AND    itb_mseg-ebelp > itb_ekpo-ebelp ).
            w_index_mseg = sy-tabix.
            EXIT.
          ENDIF.
        ENDLOOP.
        APPEND itb_pca.
        CLEAR itb_pca.
    FAE26446 suppression parag. suivant
         ELSEIF itb_ekpo-ebeln > itb_ekko-ebeln.
           w_index_ekpo = sy-tabix.
           EXIT.
         ENDIF.
       ENDLOOP.
    Fin FAE26446
      ENDLOOP.
    Thanks in advance for all.....

    Hi
    these are the performance tips
    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.
    <b>Internal Tables</b>
    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.
    <b>Reward if usefufll</b>

Maybe you are looking for

  • IPod (dock connector) stuck in disk mode

    i just replaced the HD on my iPod(dock connector)and now it stuck on disk mode. i tried to reset but it showed a folder with an exclaimation point and went back to disk mode flashing the "do not" symbol and "do not disconnect". it don't show up on my

  • Submit button help (please)

    I have tried asking for help on this topic before, but didn't get any replies. So I try again. I have created a pdf form with a submit button that submits the form to a webservice url. I submit it as HTML. I receive the form data just fine in my webs

  • Validation rule in Funds management.

    Dear Friends, We use commitment items to monitor the budgets with overall budget for budget type Payment budget In some cases, users are posting some adjustment entries to transfer the consumed budget values from one commitment item to another. Ex: O

  • "Spam vs. Junk" in Mavericks Mail

    Up until upgrading to OS X Mavericks - in my Mail application, 2 separate folders "Junk" and "Spam" appeared, and different e-mails automatically fell into each -- my "Spam" folder disappeared upon upgrade to Mavericks...where'd it go? Do I now have

  • Can any one have TBIT50 document for XI

    Hi All, Can any one please provide me the TBIT50 XI document. i am preparing for the Certification. Thanks, Praveen Kumar B.V