Looping, Grouping and Control Levels

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

An internal table is a list of rows that lives in the memory of a running program, and almost every program has to go through such a list: to print it, to change some rows, or to add up amounts for each department. This page shows how. You will learn the plain loop, how to pick only the rows you want, how to change a row without copying it, how to build one subtotal per group in a single statement, and how to run a database-style query over the table itself. The page also explains the older "control level" statements that you will still meet in older programs. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). Looping, WHERE, field symbols, references and GROUP BY apply in ABAP Cloud and in classic, Standard ABAP (on premise and in the Public Edition). COLLECT and the control level statements are the older style: the Keyword Documentation marks the control level statements as deprecated syntax and recommends GROUP BY instead, so use GROUP BY for new code.

Before you read

  • Data Types and Data Objects: structures, internal tables and inline declarations.

  • Constructor Expressions: VALUE and REDUCE, which the grouping example uses.

  • The basics of internal tables (table kinds, keys, reading and changing single rows) are taught on the page Internal Tables, which belongs to this group of pages; here you only need to know that a table holds rows of one type.

Key terms

  • Internal table: a list of rows of the same type that exists only while the program runs.

  • Work area: a variable that holds one copy of a row while the loop is on that row.

  • Field symbol: a name that points straight at a row in the table, so a change through it changes the table itself.

  • Data reference: a variable that holds the address of a row and is followed with the -> operator.

  • Group key: the value, or the set of values, that makes rows belong to the same group.

  • Control level: a point in a sorted loop where the value of a leading column changes, used by the older AT NEW and AT END OF statements.

Looping over a table

LOOP AT runs its body once for each row, from the first row to the last. After LOOP AT itab INTO wa the body sees a copy of the current row in the work area wa; changing the copy does not change the table. Inside the loop the system field sy-tabix holds the position of the row in the table. ENDLOOP closes the loop.

The examples use the Expense claims data of this section. A claim item has a claim number, a cost centre and an amount.

TYPES: BEGIN OF ty_item,
         claim_id    TYPE c LENGTH 10,
         cost_center TYPE c LENGTH 6,
         amount      TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_item,
       ty_items TYPE STANDARD TABLE OF ty_item WITH EMPTY KEY.

DATA(items) = VALUE ty_items(
  ( claim_id = 'C000000001' cost_center = 'CC1000' amount = '120.00' )
  ( claim_id = 'C000000002' cost_center = 'CC2000' amount = '35.50'  )
  ( claim_id = 'C000000003' cost_center = 'CC1000' amount = '80.25'  )
  ( claim_id = 'C000000004' cost_center = 'CC3000' amount = '10.00'  )
  ( claim_id = 'C000000005' cost_center = 'CC2000' amount = '64.50'  ) ).

LOOP AT items INTO DATA(item).
  WRITE: / sy-tabix, item-claim_id, item-cost_center, item-amount.
ENDLOOP.

This listing runs in the local playground (as a report with the types and the table above it). It prints one line per claim item, numbered 1 to 5 in table order, each with the claim number, the cost centre and the amount; the playground prints the fields of a line without spaces between them and uses a decimal comma, so the first line reads 1C000000001CC1000120,00.

The work area is declared inline with DATA(item). The addition TRANSPORTING NO FIELDS copies no row at all and only fills the system fields; the Keyword Documentation allows it only together with a WHERE condition. It is the right form when you only need to know whether a matching row exists or at which position.

Picking rows with WHERE, FROM and TO

A WHERE condition makes the loop skip every row for which the condition is false, so the body only sees the matching rows. FROM and TO restrict the loop to a range of row positions; without USING KEY they can be used only for index tables (standard and sorted tables). Inserting or deleting rows of the table inside its own loop is a trap: rows inserted after the current row are visited by later passes, which can even produce an endless loop, and rows deleted after the current row are no longer visited. Collect the changes in a second table when you can.

DATA(cc1000_total) = CONV ty_item-amount( 0 ).

LOOP AT items INTO DATA(item) WHERE cost_center = 'CC1000'.
  cc1000_total = cc1000_total + item-amount.
ENDLOOP.
WRITE: / cc1000_total.

This listing runs in the local playground and prints the total of the two CC1000 items, 200,25.

Changing rows in place: ASSIGNING and REFERENCE INTO

A work area is a copy, so a change to it is lost. To change the row itself, point at the row instead of copying it. ASSIGNING makes a field symbol point at the current row, and REFERENCE INTO puts a data reference to it in a variable. Both avoid the cost of copying a wide row, which matters for big tables.

LOOP AT items ASSIGNING FIELD-SYMBOL(<item>) WHERE cost_center = 'CC3000'.
  <item>-amount = <item>-amount * 2.
ENDLOOP.

LOOP AT items REFERENCE INTO DATA(item_ref) WHERE cost_center = 'CC1000'.
  item_ref->amount = item_ref->amount + '1.00'.
ENDLOOP.

LOOP AT items INTO DATA(changed).
  WRITE: / changed-claim_id, changed-amount.
ENDLOOP.

This listing runs in the local playground. The last loop shows the table after the changes: claim 1 now has 121,00, claim 3 has 81,25 and claim 4 has 20,00, while claims 2 and 5 are unchanged (35,50 and 64,50).

A field symbol is used like the row itself (<item>-amount); a reference is followed with the arrow (item_ref->amount). Which to prefer is mostly a matter of style. One rule is firm: the key columns of the primary key of a sorted or hashed table are read-only, because a change would break the order or the hash, and an attempt to change them raises an exception that cannot be caught (the Keyword Documentation of READ TABLE, whose rules the loop shares, states this).

Grouping with LOOP AT …​ GROUP BY

A very common job is "one total per department". In older code this took a sort and control level statements (explained below). LOOP AT ... GROUP BY does it in one statement: it forms groups of rows with the same group key, and the outer loop runs once per group. Inside it you can visit the members of the current group with an inner LOOP AT GROUP, or add them up in an expression with FOR ... IN GROUP.

flowchart TD A[Internal table of claim items] --> B[LOOP AT items GROUP BY cost_center] B --> C{Next group?} C -- yes --> D[Group key, for example CC1000] D --> E[Inner LOOP AT GROUP visits the members] E --> F[Subtotal for the group] F --> C C -- no --> G[Done: one subtotal per cost centre]

The next example, written for a program where items is filled as above, builds one line per cost centre with the number of items and their total. It requires an SAP system; not run here (the local playground cannot transpile GROUP BY).

TYPES: BEGIN OF ty_total,
         cost_center TYPE c LENGTH 6,
         lines       TYPE i,
         amount      TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_total,
       ty_totals TYPE STANDARD TABLE OF ty_total WITH EMPTY KEY.

DATA totals TYPE ty_totals.

LOOP AT items INTO DATA(item) GROUP BY item-cost_center INTO DATA(cost_center).
  DATA(total) = VALUE ty_total( cost_center = cost_center ).
  LOOP AT GROUP cost_center INTO DATA(member).
    total-lines  = total-lines + 1.
    total-amount = total-amount + member-amount.
  ENDLOOP.
  APPEND total TO totals.
ENDLOOP.

Here item is the work area for the first row of each group and is used only to write the group key expression; cost_center receives the group key. When the key is made of several columns, write it as a structure of named components and read them from the group variable. This example also requires an SAP system; not run here.

LOOP AT items INTO DATA(item) GROUP BY ( cc = item-cost_center  big = xsdbool( item-amount > 50 ) )
     INTO DATA(group).
  DATA(count) = 0.
  LOOP AT GROUP group ASSIGNING FIELD-SYMBOL(<member>).
    count = count + 1.
  ENDLOOP.
  WRITE: / group-cc, group-big, count.
ENDLOOP.

The group key may be an expression, as big shows, so you can group by a computed value. Groups come out in the order in which their first row appears in the table; adding ASCENDING or DESCENDING after the key sorts the groups instead. Adding WITHOUT MEMBERS after the key tells the system that you will not read the members, so it does not keep the assignment of rows to groups, which the Keyword Documentation says improves performance; it needs a group variable (INTO, ASSIGNING or REFERENCE INTO) to receive the key.

Totals without an inner loop

When all you need is one value per group, REDUCE with FOR ... IN GROUP gives the total inside an expression. This also requires an SAP system; not run here.

LOOP AT items INTO DATA(item) GROUP BY item-cost_center INTO DATA(cost_center).
  DATA(total) = REDUCE ty_item-amount( INIT sum = CONV ty_item-amount( 0 )
                                        FOR member IN GROUP cost_center
                                        NEXT sum = sum + member-amount ).
  WRITE: / cost_center, total.
ENDLOOP.

COLLECT, the older shortcut

COLLECT wa INTO itab adds a row to a table in one step: if a row with the same primary key already exists, the numeric columns of the new row are added to it, otherwise the row is inserted. Every column that is not part of the primary key must be numeric. The Keyword Documentation says the statement is not suitable for standard tables and should no longer be used for them; sorted tables (with a unique key) and hashed tables are fine. The example below requires an SAP system; not run here (it gives wrong results in the local playground).

DATA sums TYPE SORTED TABLE OF ty_total WITH UNIQUE KEY cost_center.

LOOP AT items INTO DATA(item).
  COLLECT VALUE ty_total( cost_center = item-cost_center lines = 1 amount = item-amount ) INTO sums.
ENDLOOP.

COLLECT hides the grouping rule in the table key, so a change of the key changes the result silently. GROUP BY shows the rule in the statement, so prefer it for new code.

Reading a table with SELECT FROM @itab

ABAP SQL can use an internal table as its data source: write the table, with the escape character @, where a database table would stand, and give it an alias with AS. The query can then filter, sort and compute with ABAP SQL syntax that the statements for internal tables do not offer, and it needs no loop. This requires an SAP system; not run here.

SELECT cost_center, SUM( amount ) AS total, COUNT( * ) AS lines
  FROM @items AS i
  GROUP BY cost_center
  ORDER BY cost_center
  INTO TABLE @DATA(per_cost_center).

The result is the same list of totals as the loop, written as a query. There are limits: the row type may not contain strings (other than the dictionary type SSTRING), references, internal tables or sub-structures, and the internal table should have an explicitly defined primary key. The Keyword Documentation also notes that reading an internal table with SELECT is usually less efficient than the statements for internal tables, so use it when those statements cannot do the job. ABAP SQL itself is taught on the pages that follow in this section.

Older material you may meet: control levels and pre-7.40 style

Programs and books from before inline declarations and GROUP BY do totals with control level statements inside a loop over a sorted table. You will read them in maintenance work, but the Keyword Documentation lists them as deprecated syntax that is supported only temporarily in the current language version and should be replaced:

  • AT FIRST and AT LAST run once, when the first row and the last row are read.

  • AT NEW col runs when the value of col, or of any column to the left of it, differs from the previous row. AT END OF col runs at the end of such a group of rows.

  • The groups are formed from consecutive rows that agree in the control column and in all columns to its left, so the grouping columns must be the leftmost columns of the row and the table must be in a matching order (normally sorted by those columns).

  • Inside an AT block, when you loop with INTO, the character-like columns to the right of the control column hold * and the other columns to the right hold their initial value, so the amounts there are not usable. The row content returns when the block ends.

  • The table must not be modified inside the loop, and AT cannot be used inside a GROUP BY loop.

The following listing runs in the local playground. It prints a heading line before each cost centre group (CC1000, CC2000, CC3000) followed by the claim lines of that group, for example claims 1 and 3 under CC1000.

DATA(sorted_items) = items.
SORT sorted_items BY cost_center.

LOOP AT sorted_items INTO DATA(row).
  AT NEW cost_center.
    WRITE: / 'Cost centre', row-cost_center.
  ENDAT.
  WRITE: / row-claim_id, row-amount.
ENDLOOP.

The classic style has other differences that older books show: header lines (an obsolete work area with the name of the table) with LOOP AT itab. without a result part, DATA: wa LIKE LINE OF itab instead of inline declarations, COLLECT for totals, and READ TABLE with WITH KEY instead of table expressions. Current code declares variables inline, uses GROUP BY and constructor expressions, and avoids sorting just to trigger a control level.

Summary

  • LOOP AT itab INTO wa copies each row; ASSIGNING and REFERENCE INTO point at the row so you can change it.

  • WHERE limits the loop to matching rows; TRANSPORTING NO FIELDS (with WHERE) only reports positions.

  • LOOP AT ... GROUP BY forms groups in one statement; LOOP AT GROUP and FOR ... IN GROUP read the members.

  • COLLECT, AT NEW and AT END OF are older (the control level statements are marked deprecated): prefer GROUP BY for new code.

  • SELECT FROM @itab runs an ABAP SQL query over an internal table.

Try it

To do this by hand, follow the guide Work with Internal Tables: it builds claim items with VALUE, reads them with table expressions, sorts, groups and totals them.