Search code examples
abapinternal-tables

How is the internal table sorted by default?


So i was wondering if when i declare

lt_table TYPE STANDARD TABLE OF mara.

Is it the same as

lt_table TYPE STANDARD TABLE OF mara WITH DEFAULT KEY.

Or are the standard table keys selected differently when not declaring DEFAULT KEY?


Solution

  • That's the same, as explained in the ABAP documentation:

    If no explicit primary key is defined for a standard table, it automatically has a standard key.

    A standard key is when you indicate DEFAULT KEY (first bullet point below) or nothing (second one):

    The standard key can be declared as follows:

    • Explicitly, using the additions UNIQUE|NON-UNIQUE KEY of the statements TYPES, DATA and so on, where the addition DEFAULT KEY is specified instead of the list of components.
    • Implicitly, if no explicit primary key specification is made in the declaration of a standard table with the statement DATA.
    • Implicitly, if a standard table type with a generic primary table key is specified behind TYPE in the statement DATA.

    EDIT May 31st, 2022: there can be some confusion about the meaning of the "keys of a standard table". That could make people think that the table is sorted and the access is then faster.

    That's wrong.

    It will be faster only if you sort explicitly your internal table SORT itab BY comp1 comp2 (once as it's time consuming), and use READ TABLE itab WITH KEY comp1 = ... comp2 = ... BINARY SEARCH.

    Declaring the primary key (default key or explicit components) of a standard table is a way to not mention the components after SORT, READ TABLE, etc., but the ABAP documentation recommends to explicitly declare them after SORT, READ TABLE, etc.

    Consequently, I don't see any interest in declaring the primary key of a standard table.

    NB: COLLECT works only based on the primary key of the standard table, so here there's no choice except if you replace COLLECT with code like this for instance:

    ASSIGN itab[ c1 = line-c1 c2 = line-c2 ] TO FIELD-SYMBOL(<exist_line>).
    IF sy-subrc = 0.
      <exist_line>-counter = <exist_line>-counter + line-counter.
    ELSE.
      INSERT line INTO TABLE itab.
    ENDIF.
    

    If you want to use a sorted table for faster access, prefer declaring the table with TYPE SORTED TABLE or TYPE HASHED TABLE (or any alternate syntax to have Secondary Keys), it will really sort the table and accesses are faster, the compiler will send better warning or error messages with SORT (error because already sorted), READ TABLE, etc., than for a standard table (only some warnings if you use ATC).

    For more information, see ABAP documentation - itab - Selection of the Table Category