ABAP Keyword Documentation → ABAP − Reference → Processing Internal Data → Internal Tables → Processing Statements for Internal Tables → SORT itab
Sorting Internal Tables with Secondary Keys
This example demonstrates how tables with secondary table keys are sorted.
Other versions: 7.31 | 7.40 | 7.54
Source Code
DATA: BEGIN OF struct,
col1 TYPE c LENGTH 1,
col2 TYPE c LENGTH 1,
END OF struct.
DATA itab LIKE STANDARD TABLE OF struct
WITH NON-UNIQUE KEY col1
WITH UNIQUE HASHED KEY sec_key COMPONENTS col2.
DATA jtab LIKE itab.
DATA(out) = cl_demo_output=>new( ).
itab = VALUE #( ( col1 = 'A' col2 = '1' )
( col1 = 'A' col2 = '2' )
( col1 = 'B' col2 = '3' )
( col1 = 'B' col2 = '4' ) ).
LOOP AT itab INTO struct.
APPEND struct TO jtab.
ENDLOOP.
out->write_data( jtab ).
CLEAR jtab.
SORT itab BY col2 DESCENDING.
LOOP AT itab INTO struct.
APPEND struct TO jtab.
ENDLOOP.
out->write_data( jtab ).
CLEAR jtab.
LOOP AT itab INTO struct USING KEY sec_key.
APPEND struct TO jtab.
ENDLOOP.
out->write_data( jtab ).
out->display( ).
Description
The table itab
has a secondary hash key for the column col2
.
If the table is sorted in descending order using this column, the primary index is applied accordingly
and a LOOP
without a key produces the new order. If, however,
USING KEY
is used to specify the secondary hash key in the loop, the table is processed in the order in which it was filled.