Internal Tables Part 5: SORT, BINARY SEARCH and Secondary Keys
Preview · a free account unlocks the full lesson
Make key reads fast on standard tables with SORT and BINARY SEARCH, understand why the sort order must match, and use secondary keys when one table needs several access paths.
In this lessonShow sectionsHide sections
Visual overview
Explanation
Part 4 covered reading rows by key, which on standard tables can be slow for large volumes. This part fixes that the classic way and the modern way, and shows a dangerous trap to avoid.
SORT puts the table in order, for example SORT gt_book BY carrid connid fldate. or SORT gt_book BY forcuram DESCENDING. The default order is ascending, and adding STABLE keeps the relative order of rows that are equal on the sort key. Sorting costs time, so do it once after filling the table rather than repeatedly.
Once the table is sorted, READ TABLE gt_book INTO gs_book WITH KEY carrid = 'LH' connid = '0400' BINARY SEARCH performs a fast logarithmic lookup instead of a linear scan.
For this to work correctly, the table must be sorted ascending by exactly the same fields, in the same order, as the key used in the read (the leading fields). sy-subrc comes back 0 when the row is found, 4 when it is not found (with sy-tabix giving the insert position), and 8 when it is not found and the position would be beyond the last row.
With non-unique keys, BINARY SEARCH finds the first matching row, which is useful as the starting point for a parallel cursor technique covered later. The real danger is that if the sort order does not match the key used, BINARY SEARCH can report "not found" for rows that actually exist — a silent bug that is easy to miss.
Create a free account to keep reading
You have read the opening of this lesson. A free ERPClimb account unlocks the rest of it, every other lesson and topic, and your learning history, so you can pick up exactly where you stopped. No card needed.
- Full explanation
- Code example
- Real project scenario
- Common mistakes
- Best practices
- Interview angle
One tap with Google works too. Every topic keeps its first lesson open to everyone.
Keep exploring
Check before use: lesson examples are educational, not a guarantee of correctness for your SAP edition or release. Sample code has not been executed on your SAP system. Confirm API availability, syntax, authorizations and business impact in an approved development or test environment.