FOR ALL ENTRIES: Correct Use and Hidden Risks
Use FOR ALL ENTRIES safely by checking empty driver tables and removing duplicates.
Explanation
FOR ALL ENTRIES is commonly used to fetch dependent data for a set of keys. It can perform well when used correctly, but it has dangerous mistakes. If the driver table is empty, the SELECT may ignore the FOR ALL ENTRIES condition and fetch too much data. If the driver table has duplicates, it can increase DB work unnecessarily. The driver table should be checked for initial value and deduplicated before the SELECT. In modern Open SQL, JOINs may be better when data relationship is clear and filtering can be pushed to DB.
Code example
* Purpose:* Safe FOR ALL ENTRIES pattern.* Driver table must not be empty and should not contain duplicates. DATA lt_ebeln TYPE SORTED TABLE OF ebeln WITH UNIQUE KEY table_line. * Collect unique purchase orders from header resultLOOP AT lt_ekko INTO DATA(ls_ekko). INSERT ls_ekko-ebeln INTO TABLE lt_ebeln.ENDLOOP. * Critical guard:* Never run FOR ALL ENTRIES with an empty driver table.IF lt_ebeln IS NOT INITIAL. SELECT ebeln, ebelp, matnr, menge FROM ekpo INTO TABLE @DATA(lt_ekpo) FOR ALL ENTRIES IN @lt_ebeln WHERE ebeln = @lt_ebeln-table_line. ENDIF.Real project scenario
An MM report accidentally fetched almost all EKPO records because the FOR ALL ENTRIES driver table was empty. Adding an initial check prevented a production memory issue.
Common mistakes
- FOR ALL ENTRIES with empty driver table. - Not removing duplicate keys. - Selecting too many columns. - Using FAE when JOIN is cleaner.
Best practices
- Always check driver table is not initial. - Deduplicate driver keys. - Select only required columns. - Consider JOIN or CDS where suitable.
Interview angle
A strong answer must mention the empty driver table risk and duplicate removal.