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

SORT itab

Quick Reference

Syntax

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


Extras:

1. ... STABLE

2. ... ASCENDING|DESCENDING

3. ... AS TEXT

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

5. ... BY (otab)

6. ... BY expr

Effect

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

If no explicit sort key is entered using the addition BY, 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, no sort takes place. If this is known statically, the syntax check produces a warning.

Sorting is unstable by default, which means that the relative order of rows that do not have different sort keys is not preserved when they are sorted. The order can be different depending on the platform or when sorted multiple times. The addition STABLE can be used for stable sorting.

itab expects a standard table or a hashed table.

In both table categories, 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 statement SORT to sorted tables is prohibited by the syntax. If the system only detects that a sorted table is to be sorted at runtime, a non-handleable exception is raised if this action could modify the existing sorting. The latter occurs in the following cases:

Otherwise, the statement SORT is ignored for sorted tables.

Notes

Example

Simplest form of statement SORT for internal tables. The hash table carriers is sorted by its primary key (in other words, sorted by column carrid).

DATA carriers TYPE HASHED TABLE OF scarr
              WITH UNIQUE KEY carrid.

SELECT *
       FROM scarr
       INTO TABLE @carriers.

SORT carriers.

Executable Examples

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. If the STABLE addition is not specified, the order is not stable:

Example

Stabile sorting of internal table flights by columns cityfrom cityto, whereby the order within this sorting with regards to carrid and connid remains the same.

SELECT carrid, connid, cityfrom, cityto
       FROM spfli
       ORDER BY carrid, connid
       INTO TABLE @DATA(flights).

SORT flights STABLE BY cityfrom cityto.

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 specified, the table is sorted in ascending order. This sort direction can be overwritten after the addition BY for components specified individually here.

Example

The internal table itab is sorted by its primary key (in other words, by its rows). Next, LOOP AT GROUP BY can be used for grouping and determine the number of rows per group.

DATA itab TYPE TABLE OF i WITH NON-UNIQUE KEY table_line.

DATA(rnd) = cl_abap_random_int=>create( seed = + sy-uzeit
                                        min  = 1
                                        max  = 10 ).

itab = VALUE #( FOR i = 1 UNTIL i > 100 ( rnd->get_next( ) ) ).

SORT itab DESCENDING.

LOOP AT itab ASSIGNING FIELD-SYMBOL(<fs>)
             GROUP BY ( key = <fs> size = GROUP SIZE )
             ASSIGNING FIELD-SYMBOL(<key>).
  cl_demo_output=>write( |{ <key>-key WIDTH = 4
                         }{ <key>-size }| ).
ENDLOOP.
cl_demo_output=>display( ).

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 can be overwritten after the addition BY for the components specified individually here. The text environment is set when an internal session is opened or by using the statement SET LOCALE.

Notes

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 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.
ENDCLASS.

CLASS demo IMPLEMENTATION.
  METHOD main.
    text_tab = VALUE #(
      ( `Muller` )
      ( `Möller` )
      ( `Moller` )
      ( `Miller` ) ).
    SORT text_tab.
    cl_demo_output=>write_data( text_tab ).
    SORT text_tab AS TEXT.
    cl_demo_output=>display_data( text_tab ).
  ENDMETHOD.
ENDCLASS.

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

Executable Example

Sorting Internal Tables Alphabetically

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, 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 addition AS TEXT is not specified after a text-like component compi, the instructions defined by addition 3 are 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

Example

Sorting in ascending order of internal table itab by column col1 and sorting in descending order by column col2.

TYPES:
  BEGIN OF line,
    col1 TYPE c LENGTH 1,
    col2 TYPE i,
  END OF line.

DATA itab TYPE STANDARD TABLE OF line WITH EMPTY KEY.

itab = VALUE #( ( col1 = 'A' col2 = 6 )
                ( col1 = 'B' col2 = 4 )
                ( col1 = 'B' col2 = 7 )
                ( col1 = 'C' col2 = 1 )
                ( col1 = 'C' col2 = 3 )
                ( col1 = 'B' col2 = 9 )
                ( col1 = 'A' col2 = 2 )
                ( col1 = 'A' col2 = 5 )
                ( col1 = 'C' col2 = 8 ) ).

SORT itab BY col1 ASCENDING col2 DESCENDING.

cl_demo_output=>display( itab ).

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:

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

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 (which the table is to be sorted by) can be entered.

DATA dbtab TYPE c LENGTH 30 VALUE 'spfli'.
cl_demo_input=>add_field( CHANGING field = dbtab ).
DATA columns TYPE string VALUE `cityfrom, cityto`.
cl_demo_input=>request( CHANGING field = columns ).
dbtab = condense( to_upper( dbtab ) ).

DATA dref TYPE REF TO data.
FIELD-SYMBOLS <itab> TYPE STANDARD TABLE.

TRY.
    CREATE DATA dref TYPE STANDARD TABLE OF (dbtab).
    ASSIGN dref->* TO <itab>.
  CATCH cx_sy_create_data_error.
    cl_demo_output=>display( 'Wrong data type!' ).
    LEAVE PROGRAM.
ENDTRY.

TRY.
    SELECT *
           FROM (dbtab)
           INTO TABLE @<itab>.
  CATCH cx_sy_dynamic_osql_semantics.
    cl_demo_output=>display( 'Wrong database table!' ).
    LEAVE PROGRAM.
ENDTRY.

SPLIT columns AT `,` INTO TABLE DATA(column_tab).
DATA(order) = VALUE abap_sortorder_tab(
                FOR wa IN column_tab
               ( name = condense( to_upper( wa ) ) ) ).

TRY.
    SORT <itab> BY (order).
  CATCH cx_sy_dyn_table_ill_comp_val.
    cl_demo_output=>display(  'Wrong column name!' ).
    LEAVE PROGRAM.
ENDTRY.

cl_demo_output=>display( <itab> ).

Addition 6

... BY expr

Effect

The addition BY expr can be used to specify an expression or a functional method call expr whose result is an internal table with the same type and content as in the preceding addition BY (otab). expr is a general expression position. The behavior is the same as when specifying a parenthesized internal table directly.

Note

Parentheses cannot be placed around expr.

Example

The above example for specifying BY (otab) can be written in a shorter form as shown below. Instead of specifying the unnecessary internal table order, you can specify the tabular value (constructed using value operator VALUE) of the required content.

...

SPLIT columns AT `,` INTO TABLE DATA(column_tab).
TRY.
    SORT <itab> BY VALUE #( FOR wa IN column_tab
                ( name = condense( to_upper( wa ) ) ) ).
  CATCH cx_sy_dyn_table_ill_comp_val.
    cl_demo_output=>display(  'Wrong column name!' ).
    LEAVE PROGRAM.
ENDTRY.

...


Executable Example

Sorting Internal Tables Dynamically.

Exceptions

Non-Handleable Exceptions

CX_SY_DYN_TABLE_ILL_LINE_TYPE

CX_SY_DYN_TABLE_ILL_COMP_VAL

Non-Handleable Exceptions



Continue
Example Sorting Internal Tables
Example Sorting Internal Tables with Secondary Keys
Example Sorting Internal Tables Alphabetically
Example Sorting Internal Tables Dynamically