Table Expressions and Secondary Keys

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 your program, and one of the most common jobs is to fetch a single row from it: the claim with a given number, the item in position three. ABAP gives you two ways to do that. A table expression is a short piece of code that you write right where you need the row, and the older READ TABLE statement fetches the row into a variable on a line of its own. This page shows both, explains what happens when the row does not exist, and explains secondary keys, which are extra search paths you can add to a table so that a lookup does not have to read every row. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). Table expressions, READ TABLE and secondary keys are available in ABAP Cloud and in classic, Standard ABAP alike, so the examples apply on premise and in the Public Edition.

Before you read

Key terms

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

  • Table expression: an operand written as the table name followed by square brackets that selects one row of the table.

  • Table key: the columns the system uses to find rows quickly, either the primary key chosen with the table or a secondary key added to it.

  • Secondary key: an additional named key of a table that gives a second way to search, at the price of extra memory and upkeep.

  • Hashed table: a table kind whose rows are found through a calculated address, so a lookup by its unique key takes about the same time however many rows there are.

  • Sorted table: a table kind that keeps its rows in key order and finds a row by halving the search range again and again.

  • Exception: an event that interrupts the program when something goes wrong, which you can catch with TRY and CATCH.

Reading one row with a table expression

A table expression is the name of an internal table followed by square brackets. Inside the brackets you say which row you want, and the whole expression stands for that row, so you can use it anywhere a structure or a component is allowed. There are three ways to name the row.

  • By position: itab[ 3 ] is the third row.

  • By the value of components: itab[ claim_id = 'C-1001' ] is the first row whose component claim_id has that value. Several comparisons in the brackets all have to be true.

  • By a named key: itab[ KEY by_id COMPONENTS claim_id = 'C-1001' ] asks the system to use the key by_id, described in the section on secondary keys below.

You can also read a single component in the same expression, for example itab[ claim_id = 'C-1001' ]-amount. When the brackets hold components and no key is named, a plain standard table is searched by reading the rows one after another; the Keyword Documentation describes this as a linear search.

A table expression is only an operand, so it needs a row to exist. If no row matches, ABAP raises the exception CX_SY_ITAB_LINE_NOT_FOUND. Unlike the statement READ TABLE, which reports a failure through sy-subrc, an unhandled exception ends the program with a runtime error. Three situations do not raise it: line_exists( ) returns false, line_index( ) returns 0, and a default value given in a VALUE expression is used. So there are three ways to deal with a missing row:

  • Ask first with line_exists( ), which returns true or false.

  • Give a fallback with the additions OPTIONAL or DEFAULT of the VALUE expression.

  • Catch the exception with TRY and CATCH.

The next listing reads claim items with each of the techniques. It runs in the local playground (inside a report, with WRITE statements added to show the results).

TYPES: BEGIN OF ty_item,
         claim_id TYPE c LENGTH 10,
         position TYPE i,
         amount   TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_item,
       tt_item TYPE STANDARD TABLE OF ty_item WITH EMPTY KEY.

DATA(items) = VALUE tt_item( ( claim_id = 'C-1001' position = 1 amount = '25.00' )
                             ( claim_id = 'C-1001' position = 2 amount = '40.50' )
                             ( claim_id = 'C-1002' position = 1 amount = '12.00' ) ).

" By position and by component values: the row must exist.
DATA(second) = items[ 2 ].
WRITE / second-amount.
DATA(first_of_1002) = items[ claim_id = 'C-1002' position = 1 ].
WRITE / first_of_1002-amount.

" The exception when the row is missing.
TRY.
    DATA(missing) = items[ claim_id = 'C-9999' ].
  CATCH cx_sy_itab_line_not_found.
    WRITE / 'not found'.
ENDTRY.

" Ask first: line_exists( ) is true or false, line_index( ) is the position or 0.
IF line_exists( items[ claim_id = 'C-1002' ] ).
  DATA(where_is_it) = line_index( items[ claim_id = 'C-1002' ] ).
  WRITE / where_is_it.
ENDIF.

" OPTIONAL gives an initial row, DEFAULT gives a row you choose.
DATA(maybe_item) = VALUE ty_item( items[ claim_id = 'C-9999' ] OPTIONAL ).
WRITE / maybe_item-position.
DATA(or_zero) = VALUE ty_item( items[ claim_id = 'C-9999' ]
                               DEFAULT VALUE #( claim_id = 'C-9999' amount = 0 ) ).
WRITE / or_zero-claim_id.

The program printed this (the playground uses a comma as the decimal separator):

40,50
12,00
not found
3
0
C-9999

line_index( ) returns the position of the row, or 0 when the row does not exist; in the output above it printed 3, the position of the claim C-1002, and maybe_item-position printed 0 because OPTIONAL gave an initial row. Use OPTIONAL when an initial row (all components empty or zero) is a harmless answer, and DEFAULT when you need a meaningful substitute. If an initial row could be confused with a real row, prefer line_exists( ) or the exception. The Keyword Documentation advises avoiding several reads of the same row in one statement or loop: read the row once and keep it in a field symbol or a reference. Calling line_exists( ) and then a table expression for the same row reads it twice, whereas OPTIONAL or a TRY block reads it once.

Reading one row with READ TABLE

READ TABLE does the same job as a statement. It copies the row into a work area or points a field symbol at it, and it tells you the result through two system fields. sy-subrc is 0 when the row was found and 4 when it was not (a binary search can also give 8, and the addition COMPARING can give 2). sy-tabix holds the position of the row in the index that was used; with a hash key it is 0. Unlike READ TABLE, a table expression leaves sy-tabix unchanged, except in the statement ASSIGN.

The next listing runs in the local playground (inside a report, with WRITE statements added to show the results).

READ TABLE items INTO DATA(item) WITH KEY claim_id = 'C-1001' position = 2.
IF sy-subrc = 0.
  WRITE / 'found'.
  WRITE / sy-tabix.
  WRITE / item-amount.
ELSE.
  WRITE / 'not found'.
ENDIF.

READ TABLE items ASSIGNING FIELD-SYMBOL(<row>) INDEX 3.
IF sy-subrc = 0.
  <row>-amount = <row>-amount + 1.   " changes the row in the table itself
ENDIF.
WRITE / items[ 3 ]-amount.

READ TABLE items TRANSPORTING NO FIELDS WITH KEY claim_id = 'C-1002'.
DATA(found) = xsdbool( sy-subrc = 0 ).
WRITE / found.

The program printed the following, with the table items of the first listing: found, the position 2, the amount 40,50, the amount 13,00 after the change through the field symbol, and X, which stands for true.

found
2
40,50
13,00
X

The two ways compare like this. The READ TABLE statement never raises the not-found exception, but it needs a variable and a check of sy-subrc after it. The table expression fits inside other statements, which keeps the code shorter, but the missing row must be handled by one of the three techniques above. To change a row in place, use a field symbol or a data reference (READ TABLE ... ASSIGNING or a table expression with REF), because a copy in a work area is not connected to the table.

Why a lookup can be slow, and what a secondary key changes

Every internal table has a primary key. For a standard table the primary key is a plain list, so a search by component value looks at the rows one by one until it finds a match: with ten rows nobody notices, with a hundred thousand rows and a lookup inside a loop the program slows down sharply. A sorted table keeps its rows in key order and searches by halving the range. A hashed table finds a row through a calculated address, so the lookup time hardly depends on the number of rows. Those two table kinds are fast only for lookups by their primary key.

A secondary key solves the case where you must search the same table by more than one set of columns. You declare it together with the table type, give it a name, say whether it is hashed or sorted and whether it is unique (a hashed secondary key can only be unique), and list its components. A table can have up to 15 secondary keys. When you read the table you must name the key to be used: if you name nothing, the primary key is used, and the Keyword Documentation states that access through a secondary key is always optimized.

The next listing runs in the local playground (inside a report, with WRITE statements added to show the results).

TYPES: BEGIN OF ty_claim,
         claim_id TYPE c LENGTH 10,
         employee TYPE c LENGTH 8,
         status   TYPE c LENGTH 1,
         total    TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_claim,
       tt_claim TYPE STANDARD TABLE OF ty_claim WITH EMPTY KEY
                WITH UNIQUE HASHED KEY by_id COMPONENTS claim_id
                WITH NON-UNIQUE SORTED KEY by_employee COMPONENTS employee.

DATA(claims) = VALUE tt_claim( ( claim_id = 'C-1001' employee = 'E100' status = 'O' total = '65.50' )
                               ( claim_id = 'C-1002' employee = 'E200' status = 'A' total = '12.00' )
                               ( claim_id = 'C-1003' employee = 'E100' status = 'A' total = '80.00' ) ).

" A table expression that names the hashed key: one direct access.
DATA(claim) = claims[ KEY by_id COMPONENTS claim_id = 'C-1002' ].
WRITE / claim-total.

" The same lookup with READ TABLE.
READ TABLE claims INTO claim WITH TABLE KEY by_id COMPONENTS claim_id = 'C-1003'.
WRITE / claim-total.

" Go through the rows of one employee in key order with the sorted key.
LOOP AT claims INTO claim USING KEY by_employee WHERE employee = 'E200'.
  WRITE / claim-claim_id.
ENDLOOP.

" The key also helps to ask whether a row exists.
IF line_exists( claims[ KEY by_id COMPONENTS claim_id = 'C-1001' ] ).
  WRITE / 'exists'.
ENDIF.

The program printed:

12,00
80,00
C-1002
exists

The primary key of tt_claim is empty and the table is a standard table, so the keyed lookups above are the only ones that the Keyword Documentation calls optimized. The key by_id is unique, so the table cannot hold two rows with the same claim_id. The LOOP with USING KEY by_employee visits only the rows whose employee is E200, here the claim C-1002.

The figure shows how to choose a search path for one lookup.

flowchart TD A[Need one row of an internal table] --> B{Row known by position?} B -- yes --> C[itab with index in brackets] B -- no --> D{Table small or looked up once?} D -- yes --> E[Component values in brackets or READ TABLE] D -- no --> F{Searched by the primary key of a hashed or sorted table?} F -- yes --> G[Component values of the primary key] F -- no --> H[Declare a secondary key and name it with KEY] C --> I{Row may be missing?} E --> I G --> I H --> I I -- yes --> J[line_exists, OPTIONAL, DEFAULT or TRY and CATCH] I -- no --> K[Use the table expression directly]

What a secondary key costs

A secondary key is not free. The Keyword Documentation says to use secondary keys sparingly and only where the benefit outweighs the extra cost.

  • Memory: each secondary key needs administration memory in proportion to the number of rows. The documentation gives averages of 6 bytes per row for a sorted key and 18 or 30 bytes per row for a hash key.

  • Time on change: when table content changes, a secondary index may have to be updated. ABAP delays this work until the key is actually needed (lazy and delayed update), so the cost can appear at the first keyed read instead of at the change.

  • Uniqueness: a unique key allows no two rows with the same values in its components. That is useful as a check, and a problem if your data is not as unique as you thought.

  • Deleting by a secondary key: when rows of a standard table are deleted through a secondary key, the primary index has to be updated, which cannot be optimized for standard tables.

The standard case for a secondary key is a very large table that is filled once and changed rarely. Do not use one for a table with fewer than 50 rows, or for a table that is written to very often, because the gain on reads is then smaller than the cost. A small table can still justify a unique key when you want the system to enforce uniqueness.

Summary

  • A table expression such as itab[ claim_id = 'C-1001' ] gives one row as an operand; the statement READ TABLE gives the same row and reports success in sy-subrc.

  • A table expression raises CX_SY_ITAB_LINE_NOT_FOUND when no row matches. Avoid it with line_exists( ), with OPTIONAL or DEFAULT in a VALUE expression, or with TRY and CATCH; line_index( ) returns 0 for no row.

  • On a plain standard table a lookup by component values reads rows one after another, which is slow for large tables.

  • A secondary key (hashed or sorted, unique or not) gives a second, fast search path; name it with KEY in a table expression, WITH TABLE KEY in READ TABLE or USING KEY in LOOP AT.

  • A secondary key costs memory and upkeep on change, so add it only for large tables that are searched often and changed rarely.

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.