Extracting unique values from an internal table

What is the most efficient way to extract the unique values from a column or multiple columns of an internal table?


  • If you have 7.40 SP08 or above you can simply use the inline syntax to populate the target table (no need for LOOP GROUP BY):

    DATA: it_unique TYPE STANDARD TABLE OF fieldtype.
    it_unique = VALUE #(
      FOR GROUPS value OF <line> IN it_itab
      GROUP BY <line>-field WITHOUT MEMBERS ( value ) ).

    This works with any type of the target table.

    For an older release use:

    DATA: it_unique TYPE HASHED TABLE OF fieldtype WITH UNIQUE KEY table_line.
    LOOP AT it_itab ASSIGNING <line>.
      INSERT <line>-field INTO TABLE lt_unique.

    The above works with sorted tables as well. Although I do not recommend to use sorted tables for this purpose unless you are really sure that only a few lines will be in the result.

    The non-zero sy-subrc of INSERT is simply ignored. No need to do the key lookup twice (once for existence check, once for insert).

    If the target must be a STANDARD TABLE and you have an old ABAP stack you can alternatively use

    DATA: it_unique TYPE STANDARD TABLE OF fieldtype.
    LOOP AT it_itab ASSIGNING <line>.
      READ TABLE lt_unique WITH TABLE KEY table_line = <line>-field
      INSERT <line>-field INTO lt_unique INDEX sy-tabix.

    This provides the same behavior as with a sorted table but with a standard table. Whether this is more efficient than SORT / DELETE ADJACENT DUPLICATES depends on the number of duplicate entries in itab. The more duplicate entries exist the faster will be the above solution because it avoids the unnecessary appends to the target table. But on the other side appends are faster than inserts.