abap news
Home » ABAP FILTER on a Standard Table Using a Secondary Key

ABAP FILTER on a Standard Table Using a Secondary Key

ABAPBy xabap Published
Two highlighted rows leaving a funnel

FILTER copies the rows of an internal table that match a condition. It requires a sorted or hashed key for the fields in WHERE. A standard table without such a key causes a syntax error. Add a secondary sorted key and name it with USING KEY.

The fix

TYPES: BEGIN OF ts_order,
         id     TYPE i,
         status TYPE c LENGTH 1,
         amount TYPE i,
       END OF ts_order.

DATA lt_orders TYPE STANDARD TABLE OF ts_order
  WITH EMPTY KEY
  WITH NON-UNIQUE SORTED KEY by_status COMPONENTS status.

lt_orders = VALUE #( ( id = 1 status = 'O' amount = 100 )
                     ( id = 2 status = 'C' amount = 250 )
                     ( id = 3 status = 'O' amount =  75 )
                     ( id = 4 status = 'X' amount =  50 ) ).

DATA(lt_open) = FILTER #( lt_orders USING KEY by_status
                          WHERE status = 'O' ).

lt_open contains the orders 1 and 3.

The literal must match the type of the field. If your variable has a different type, convert it first, for example WHERE status = CONV #( lv_status ).

Keep everything except the matches

DATA(lt_not_open) = FILTER #( lt_orders EXCEPT USING KEY by_status
                              WHERE status = 'O' ).

lt_not_open contains the orders 2 and 4.

Filter by another table

The filter table can hold the list of allowed values. Here the key of the filter table is used:

TYPES ty_status TYPE c LENGTH 1.
DATA lt_allowed TYPE SORTED TABLE OF ty_status
  WITH UNIQUE KEY table_line.
lt_allowed = VALUE #( ( 'O' ) ( 'X' ) ).

DATA(lt_selected) = FILTER #( lt_orders IN lt_allowed
                              WHERE status = table_line ).

lt_selected contains the orders 1, 3 and 4.

Rules for the WHERE condition

Key Allowed comparisons
Hashed = for all key components
Sorted =, <>, <, >, <=, >=; the components must start at the beginning of the key

Conditions are combined with AND. OR and NOT are not possible.

FILTER or FOR … WHERE?

DATA(lt_large) = VALUE ty_orders( FOR ls_order IN lt_orders
                                  WHERE ( status = 'O' AND amount > 80 )
                                  ( ls_order ) ).

This assumes a table type declared as TYPES ty_orders LIKE lt_orders.

  • FILTER: the condition fits a key and the row type stays the same.
  • FOR ... WHERE: free conditions, or you want to build different rows.
  • DELETE itab WHERE: you do not need the original table any more.

A secondary key costs memory and must be maintained when rows change. For a single pass over a small table, FOR ... WHERE is simpler.

Sources: FILTER · SAP ABAP cheat sheets