ABAP New Syntax Lecture 5: FILTER and REDUCE with Practical Examples

ABAP NEW SYNTAX
LECTURE 5
FILTER + REDUCE

FILTER creates a new table from selected rows. REDUCE evaluates iterations to calculate one result.

Learning outcome: Filter with a suitable key, use EXCEPT, calculate totals and counts, and avoid common performance traps.

1. Prepare a keyed table

TYPES ty_orders TYPE SORTED TABLE OF ty_order
  WITH UNIQUE KEY id
  WITH NON-UNIQUE SORTED KEY status_key COMPONENTS status.

The basic FILTER form uses a sorted or hashed primary or secondary key.

2. Keep matching rows

CODE SCREEN 1 — FILTER
DATA(lt_open) = FILTER ty_orders(
  lt_orders USING KEY status_key
  WHERE status = 'O' ).

3. Exclude matching rows

DATA(lt_not_open) = FILTER ty_orders(
  lt_orders EXCEPT USING KEY status_key
  WHERE status = 'O' ).

FILTER returns a new table; the source remains unchanged.

4. FILTER vs VALUE ... FOR

  • Use FILTER to keep or exclude unchanged rows with a suitable key.
  • Use VALUE ... FOR ... WHERE when you also need to map fields.
  • Use LOOP for complex statement-based processing.

5. REDUCE: INIT, FOR and NEXT

CODE SCREEN 2 — TOTAL
DATA(lv_total) = REDUCE decfloat34(
  INIT sum = CONV decfloat34( 0 )
  FOR ls_order IN lt_orders
  NEXT sum = sum + ls_order-amount ).

6. Count selected rows

DATA(lv_open_count) = REDUCE i(
  INIT count = 0
  FOR ls_order IN lt_orders
  WHERE ( status = 'O' )
  NEXT count = count + 1 ).

7. Calculate an average safely

DATA(ls_agg) = REDUCE ty_aggregate(
  INIT result = VALUE ty_aggregate( )
  FOR ls_order IN lt_orders
  NEXT result-total = result-total + ls_order-amount
       result-count = result-count + 1 ).

DATA(lv_average) = COND decfloat34(
  WHEN ls_agg-count > 0
  THEN ls_agg-total / ls_agg-count
  ELSE 0 ).

8. Filter while reducing

DATA(lv_open_total) = REDUCE decfloat34(
  INIT sum = CONV decfloat34( 0 )
  FOR ls_order IN lt_orders WHERE ( status = 'O' )
  NEXT sum = sum + ls_order-amount ).

9. Common mistakes

  • Using basic FILTER without a suitable sorted or hashed key.
  • Forgetting USING KEY for the required secondary key.
  • Choosing an accumulator type that loses decimals.
  • Dividing by zero for an empty table.
  • Using REDUCE when a database aggregate can do the work before transfer.

10. Practice exercises

  1. Filter open orders.
  2. Exclude open orders with EXCEPT.
  3. Calculate total amount.
  4. Count selected rows.
  5. Calculate an average with empty-table handling.

11. Interview quick checks

Does FILTER modify the source?

No, it constructs a filtered result.

What does REDUCE return?

One result value, possibly a structure, built from accumulator variables.

Must REDUCE contain an iteration?

Yes, at least one iteration expression is required.

Official SAP references

Educational examples; verify keys and syntax availability for your ABAP release.

Post a Comment

0 Comments