Skip to content

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

Sorting Internal Tables

This example demonstrates how internal tables are sorted using SORT itab.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    DATA: BEGIN OF line,
            land   TYPE c LENGTH 3,
            name   TYPE c LENGTH 10,
            age    TYPE i,
            weight TYPE p DECIMALS 2,
          END OF line.

    DATA itab LIKE STANDARD TABLE OF line WITH NON-UNIQUE KEY land.

    line-land = 'G'.   line-name   = 'Hans'.
    line-age  = 20.    line-weight = '80.00'.
    APPEND line TO itab.

    line-land = 'USA'. line-name   = 'Nancy'.
    line-age  = 35.    line-weight = '45.00'.
    APPEND line TO itab.

    line-land = 'USA'. line-name   = 'Howard'.
    line-age  = 40.    line-weight = '95.00'.
    APPEND line TO itab.

    line-land = 'GB'.  line-name   = 'Jenny'.
    line-age  = 18.    line-weight = '50.00'.
    APPEND line TO itab.

    line-land = 'F'.   line-name   = 'Michele'.
    line-age  = 30.    line-weight = '60.00'.
    APPEND line TO itab.

    line-land = 'G'.   line-name   = 'Karl'.
    line-age  = 60.    line-weight = '75.00'.
    APPEND line TO itab.

    cl_abap_demo_services=>list_table( itab ).

    SORT itab.
    cl_abap_demo_services=>list_table( itab ).

    SORT itab.
    cl_abap_demo_services=>list_table( itab ).

    SORT itab STABLE.
    cl_abap_demo_services=>list_table( itab ).

    SORT itab DESCENDING BY land weight ASCENDING.
    cl_abap_demo_services=>list_table( itab ).

Description

Four sort operations are carried out on a standard table with a key field. First, the table (land) is sorted twice in succession by its key without using the STABLE addition. The sort is instable. The order of rows in which multiple keys appear can change. Next, the same sort is carried out with the STABLE addition. The sort is stable. The order of the rows remains the same. Finally, it is sorted using a new sort key, defined using land and weight. The normal sort order is descending, but for weight ascending is defined.