Internal Tables Part 4: READ TABLE, sy-subrc and Table Expressions
Preview · a free account unlocks the full lesson
Read single rows correctly: READ TABLE by index, by key and with TABLE KEY, TRANSPORTING NO FIELDS for existence checks, sy-subrc and sy-tabix — and the modern table expressions with OPTIONAL and DEFAULT.
In this lessonShow sectionsHide sections
Visual overview
Explanation
Parts 1 through 3 introduced internal tables and the basic access techniques. Reading one specific row is the single most frequent operation on a table — and also a frequent source of bugs when its result isn't checked properly.
Reading by index looks like READ TABLE gt_flight INTO gs_flight INDEX 1., and only applies to standard and sorted tables, since hashed tables have no index at all to read by.
Reading by key looks like READ TABLE gt_flight INTO gs_flight WITH KEY carrid = 'LH' connid = '0400'. Any fields at all can be used here — it's a "free key" search. On a standard table, this is a linear search unless BINARY SEARCH is added and the table is correctly sorted beforehand, a technique covered in Part 5.
On sorted or hashed tables, WITH TABLE KEY using the complete key goes through the table's own optimized access path, and even WITH KEY on the leading fields of a sorted table benefits from that same optimization.
READ TABLE … INDEX n / WITH KEY … / WITH TABLE KEY … reads one row; check sy-subrc (0 found, 4 not found). sy-subrc comes back 0 when the row is found and 4 when it isn't — or 8 specifically with BINARY SEARCH when the position would be beyond the end of the table. sy-tabix gives the index of the row that was found, on standard and sorted tables, which is useful afterward for MODIFY … INDEX or as a starting index for a following loop.
A failed READ leaves the work area unchanged — never use it without checking sy-subrc, since the work area simply keeps whatever it held before the failed read, which can silently carry stale data forward if you're not careful.
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.