Internal Tables
ABAP DevelopmentIntermediate

BINARY SEARCH, SORT and Secondary Keys

Understand when binary search helps, when it fails, and when secondary keys are better.

Explanation

BINARY SEARCH can improve READ TABLE performance on a STANDARD table, but only when the table is sorted by the exact same key used in the search. If the sort order does not match the read key, the result may be wrong or inconsistent. Secondary keys provide an additional access path for an internal table. They can make key-based processing cleaner than repeated manual SORT plus BINARY SEARCH. However, secondary keys also consume memory and must be maintained during table changes, so they should be used only when the access pattern justifies them.

Code example

ABAP Code
TYPES tt_item TYPE STANDARD TABLE OF ty_item  WITH NON-UNIQUE SORTED KEY by_delivery COMPONENTS vbeln posnr. DATA lt_item TYPE tt_item. LOOP AT lt_item ASSIGNING FIELD-SYMBOL(<ls_item>)  USING KEY by_delivery  WHERE vbeln = lv_vbeln.  WRITE: / <ls_item>-posnr.ENDLOOP.

Real project scenario

A delivery report repeatedly reads item data by delivery number and item number. Instead of repeatedly sorting or scanning a STANDARD table, a sorted secondary key can be defined for VBELN and POSNR access.

Common mistakes

- Using BINARY SEARCH without sorting. - Sorting by one key but reading by another key. - Adding secondary keys without a real access need. - Forgetting that key maintenance has memory and runtime cost.

Best practices

- Use BINARY SEARCH only after correct SORT. - Prefer clear key-based table design for repeated access. - Use secondary keys only for justified access patterns. - Measure performance before and after optimization.

Interview angle

Senior candidates should explain both the performance benefit and the maintenance/memory trade-off of secondary keys.