Skip to content

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

Sorting Internal Tables Alphabetically

This example demonstrates the alphabetical sorting of character strings.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    DATA: BEGIN OF line,
            text(6) TYPE c,
            xtext TYPE xstring,
          END OF line.

    DATA itab LIKE HASHED TABLE OF line WITH UNIQUE KEY text.

    line-text = 'Muller'(001).
    CONVERT TEXT line-text INTO SORTABLE CODE line-xtext.
    INSERT line INTO TABLE itab.

    line-text = 'M�ller'(002).
    CONVERT TEXT line-text INTO SORTABLE CODE line-xtext.
    INSERT line INTO TABLE itab.

    line-text = 'Moller'(003).
    CONVERT TEXT line-text INTO SORTABLE CODE line-xtext.
    INSERT line INTO TABLE itab.

    line-text = 'Miller'(004).
    CONVERT TEXT line-text INTO SORTABLE CODE line-xtext.
    INSERT line INTO TABLE itab.

    SORT itab.
    cl_abap_demo_services=>list_table_components(
                            table      = itab
                            components = `text` ).

    SORT itab BY xtext.
    cl_abap_demo_services=>list_table_components(
                            table      = itab
                            components = `text` ).

    SORT itab AS TEXT.
    cl_abap_demo_services=>list_table_components(
                            table      = itab
                            components = `text` ).

Description

The table itab contains a column with text fields and a column with corresponding, country-specific, binary characters that can be sorted and have been created, through conversion, in a sortable format. The table is sorted three times. First, a binary search on the key field text, then a binary search on the xtext field and finally, alphabetically on the key field text.

In the first sort 'Möller' comes after 'Muller', because the internal representation of 'ö' comes after the representation for 'u'. Both the other sorts are alphabetic. The binary sort on xtext has the same result as an alphabetic sort on the field text.