Skip to content

ABAP Keyword Documentation →  ABAP - Reference →  Processing Internal Data →  Internal Tables →  Processing Statements for Internal Tables 

SORT itab

Short Reference

Other versions: 7.31 | 7.40 | 7.54

Syntax


SORT itab [STABLE] 
          { { [ASCENDING|DESCENDING]
              [AS TEXT]
              [BY {comp1 [ASCENDING|DESCENDING] [AS TEXT]}
                  { comp2 [ASCENDING|DESCENDING] [AS TEXT]}
                  ... ] }
          | { [BY (otab)] } }.

Extras

1. ... STABLE
2. ... ASCENDING|DESCENDING
3. ... AS TEXT

4. ... BY compi [ASCENDING|DESCENDING] [AS TEXT]

5. ... BY (otab)

Effect

This statement sorts an internal table itab by the size of its components, whereby by default sizes are compared using the general comparison rules for individual operands, that is:

  • Numerical and byte-like components are sorted by their values.
  • Character-like components are sorted by default by their binary representation (code page). Textual sorting of character-like components can be performed using the addition AS TEXT.
  • The sizes of other component types are compared using the corresponding rules for reference variables, structures, and internal tables.

If no explicit sort key is entered using the BY addition, the internal table itab is sorted by the primary table key. The priority of the sort is based on the order in which the key fields are specified in the table definition. In standard keys, the sort is prioritized according to the order of the key fields in the row type of the table. If the primary table key of a standard table is empty, then no sort takes place.

Sorting is instable by default, which means that the relative order of rows that do not have different sort keys is not retained when they are sorted, and can change when you sort more than once. The addition STABLE can be used for stable sorting.

itab expects a standard table or a hashedable.

  • In standard tables, the primary table index is applied in accordance with the sort order
  • In hashed tables, the internal order is modified. This internal order was defined either by inserting rows in the internal table or by a previous sort using the statement SORT.

In both table types, SORT specifies the order in which a subsequent LOOP runs without the addition USING KEY.

Sorted tables cannot be sorted using SORT and applying the SORT statement to sorted tables is prohibited by the syntax. If the system only detects that a sorted table is to be sorted at runtime, then a non-handleable exception is raised if this action could modify the existing sorting. The latter occurs in the following cases:

  • if the addition BY is used to specify a different sort key as the initial part of the table key.
  • if the addition DESCENDING is used.
  • if the addition AS TEXT is used.
  • if an attribute of an object is specified as a component in the addition BY.

Otherwise, the statement SORT is ignored for sorted tables.


Notes

  • We recommend that you specify an explicit sort key behind BY, if possible. An implicit sort behind the primary table key (which can itself, in standard tables, be defined implicitly as a standard key) makes a program difficult to understand and possibly unpredictable.
  • When using the primary table key, note that this key can be the standard key, which can also have unexpected consequences:

  • If the row type is structured, the table is sorted by all character-like and byte-like components.

  • The standard key of a standard table can be empty.

  • You cannot declare secondary table keys as sort keys.
  • A SORT has no effect on the assignment of rows to a secondary table index.

Addition 1

... STABLE

Effect

STABLE is used to perform stable sorts, which means that the relative order of rows (an order that does not change in the sort key) remains unchanged in the sort. Without the STABLE addition, the order is not stable and multiple sorting of a table using the same sort key can result in a different order each time the table is sorted.

Addition 2

... ASCENDING|DESCENDING

Effect

The addition ASCENDING or DESCENDING can be used to specify the sort direction explicitly as ascending or descending. If neither of the additions is specifed, the table is sorted in ascending order. This sort direction can be overwritten after the BY addition for components that are individually listed there.

Addition 3

... AS TEXT

Effect

The addition AS TEXT specifies that text-like components are sorted in accordance with the locale of the current text environment. If AS TEXT is not specified, text-like components are sorted according to the encoding in the code page of the current text environment. This specification can be overwritten after the BY addition for the components that are individually listed there. The text environment is set when an internal session is opened or by using the statement SET LOCALE.


Notes

  • The result of sorting without the AS TEXT addition depends on the operating system of the application server. Although the sequence of individual letters that belong to the activated language remains the same across different operating systems, there are differences in terms of the characters that do not belong to the alphabet of the activated language. Even if only the letters from the alphabet of the activated language are used, some slight differences occur when sorting complete words. Furthermore, the order of uppercase and lowercase letters is specific to the operating system.
  • For the addition AS TEXT to function correctly, the profile parameter install/collate/active cannot have the value 0.
  • The use of the AS TEXT addition usually renders the statement CONVERT TEXT superfluous in the context of internal tables.
  • A sort without the addition AS TEXT is considerably faster than a sort that does use this addition. If it is certain that both sorts produce the same order, then the addition AS TEXT is not necessary. This can be the case if, for example, text-like components contain characters from the ASCII character set only and only lowercase or uppercase letters.

Example

Sorting a hashed table text_tab by the order in the code page and in accordance with the locale of the current text environment. If a western European text environment is configured, the sorts produce the orders Miller, Moller, Muller, Möller and Miller, Moller, Möller, Muller respectively (also see the executable example and the example for SET LOCALE).

CLASS demo DEFINITION. 
  PUBLIC SECTION. 
    CLASS-METHODS main. 
  PRIVATE SECTION. 
    CLASS-DATA text_tab TYPE HASHED TABLE OF string 
               WITH UNIQUE KEY table_line. 
    CLASS-METHODS write_text_tab. 
ENDCLASS. 

CLASS demo IMPLEMENTATION. 
  METHOD main. 
    INSERT: `Muller` INTO TABLE text_tab, 
           `Möller` INTO TABLE text_tab, 
            `Moller` INTO TABLE text_tab, 
            `Miller` INTO TABLE text_tab. 
    SORT text_tab. 
    write_text_tab( ). 
    SORT text_tab as text. 
    write_text_tab( ). 
  ENDMETHOD. 
  METHOD write_text_tab. 
    FIELD-SYMBOLS <line> TYPE string. 
    LOOP AT text_tab ASSIGNING <line>. 
      WRITE / <line>. 
    ENDLOOP. 
    SKIP. 
  ENDMETHOD. 
ENDCLASS. 

START-OF-SELECTION. 
  demo=>main( ). 

Addition 4

... BY compi [ASCENDING|DESCENDING] [AS TEXT]

Effect

The addition BY compi does not sort the table by the primary table key, but by the components comp1 comp2... specified after it instead. The components are specified as described under Specifying Components. If all components are specified using name variables and these variables contain only blanks, then no sort takes place. The priority of the sort depends on the order in which the components comp1 comp2 ... are specified from left to right. The specified components can also be duplicated or can overlap. The specified components can have any data type. The relevant comparison rules apply to the evaluation.

If neither of the additions ASCENDING or DESCENDING are specified after compi, the sort direction specified by addition 2 is used. If one of the additions ASCENDING or DESCENDING is specified, it overwrites the default for this component.

If the AS TEXT addition is not specified after a text-like component compi, the specification defined by addition 3 is used. If the addition AS TEXT is specified after a text-like component, it overwrites the default for this component. In non-text-like components, AS TEXT cannot be specified, unless a structured component is specified. In structured components, AS TEXT only affects text-like components.


Notes

  • Instead of individual dynamic components, the internal table otab can be specified as a dynamic sort key (see addition 5). Using this table has the advantage that any exceptions are handleable. When specifying the table, the number of components of the sort key is also dynamic. In contrast, when individual dynamic components are used, a character-like data object must be specified for any required component, which is ignored if it only contains blank characters.
  • An obsolete variant allows field symbols to also be specified for the components outside of classes, for standard tables.

Addition 5

... BY (otab)

Effect

The addition BY (otab) does not sort the table by the primary table key, but by the component specified dynamically in the internal table otab instead. Each row of the table otab defines a component of the sort key. The priority of the sort is based on the order of the rows in otab. If the table otab is initial, the table is not sorted.

For otab, a standard table of the table type ABAP_SORTORDER_TAB from ABAP Dictionary must be specified. The row type of this table is the dictionary structure ABAP_SORTORDER with the following components:

  • NAME of type SSTRING
    for specifying a component of the sort key. The component is entered in the form "comp_name[+off(len)]", where "comp_name" must be the name of a component in itab in uppercase to which an offset/length "+off(len)" can be appended. "off" and "len" must be suitable numeric values.
  • DESCENDING of the type CHAR of a length 1
    for specifiying the sort direction for the current component. If DESCENDING is initial, the sort is performed in ascending order. If DESCENDING has the value "X", the table is sorted in descending order.
  • ASTEXT of type CHAR with length 1
    for the text sorting of the current component. If ASTEXT has the value "X", the sort is performed as with the AS TEXT addition. This is only possible for character-like components. If ASTEXT is initial, character-like components are sorted in accordance with their binary representation.

If a column of otab has invalid content (that is, if NAME contains the name of a component that does not exist or an incorrect offset/length or if DESCENDING and ASTEXT do not contain "X" or the initial value), this raises a handleable exception of the class CX_SY_DYN_TABLE_ILL_COMP_VAL.


Notes

  • The addition BY (otab) cannot be combined with BY compi.
  • When using the addition BY (otab), it is not possible to use DESCENDING or AS TEXT to specify a descending sort direction or textual sorting for all components.
  • If a single parenthesized data object (dobj) is specified after the BY addition, its data type decides whether its content is used to specify a single component or multiple components. In either case, no sort takes place if dobj is initial.

Example

Dynamic import of a database table into a dynamic internal table and dynamic sorting of its content. The name of the database table and the names of the columns by which the table is to be sorted can be entered in a selection screen.

PARAMETERS dbtab TYPE c LENGTH 30. 

SELECT-OPTIONS columns FOR dbtab NO INTERVALS. 

DATA: otab  TYPE abap_sortorder_tab, 
      oline TYPE abap_sortorder, 
      dref  TYPE REF TO data. 

FIELD-SYMBOLS: <column> LIKE LINE OF columns, 
               <itab> TYPE STANDARD TABLE. 

TRY. 
    CREATE DATA dref TYPE STANDARD TABLE OF (dbtab). 
    ASSIGN dref->* TO <itab>. 
  CATCH cx_sy_create_data_error. 
    MESSAGE 'Wrong data type!' TYPE 'I' DISPLAY LIKE 'E'. 
    LEAVE PROGRAM. 
ENDTRY. 

TRY. 
    SELECT * 
           FROM (dbtab) 
           INTO TABLE <itab>. 
  CATCH cx_sy_dynamic_osql_semantics. 
    MESSAGE 'Wrong database table!' TYPE 'I' DISPLAY LIKE 'E'. 
    LEAVE PROGRAM. 
ENDTRY. 

LOOP AT columns ASSIGNING <column>. 
  oline-name = <column>-low. 
  APPEND oline TO otab. 
ENDLOOP. 

TRY. 
    SORT <itab> BY (otab). 
  CATCH cx_sy_dyn_table_ill_comp_val. 
    MESSAGE 'Wrong column name!' TYPE 'I' DISPLAY LIKE 'E'. 
    LEAVE PROGRAM. 
ENDTRY. 

Exceptions


Non-Catchable Exceptions

CX_SY_DYN_TABLE_ILL_LINE_TYPE

  • Cause: The table otab has a prohibited line type.
    Runtime Error: DYN_TABLE_ILL_LINE_TYPE

CX_SY_DYN_TABLE_ILL_COMP_VAL

  • Cause: A column of the table otab contains a prohibited value.
    Runtime Error: DYN_TABLE_ILL_COMP_VAL


Non-Catchable Exceptions

  • Cause: A sort criterion dynamically specified in the form (name) with the explicit addition AS TEXT is not text-like.
    Runtime Error: SORT_AS_TEXT_BAD_DYN_TYPE
  • Cause: A field symbol used as a dynamic sort criterion with an explicit addition AS TEXT is not text-like.
    Runtime Error: SORT_AS_TEXT_BAD_FS_TYPE
  • Cause: A field symbol used as a dynamic sort criterion does not point to the header row of the internal table to be sorted.
    Runtime Error: SORT_ITAB_FIELD_INVALID
  • Cause: For a table of the type SORTED TABLE, the sort key does not match a beginning piece of the table key.
    Runtime Error: SORT_SORT_ILL_KEY_ORDER
  • Cause: The additions DESCENDING and AS TEXT are not allowed for tables of the type SORTED TABLE.
    Runtime Error: SORT_SORT_ILLEGAL
  • Cause: More than 250 sort criteria.
    Runtime Error: SORT_TOO_MANY_FIELDS
  • Cause: Sort mode neither 'E'(xternal) nor 'I'(nternal)
    Runtime Error: SORT_ILLEGAL_MODE

Continue

Sorting Internal Tables

Sorting Internal Tables Alphabetically

Sorting Internal Tables with Secondary Keys