Back to Shorts

How to sort an internal table dynamically in ABAP?

Put the field name variable in parentheses in the BY clause.

DATA lt_flights TYPE TABLE OF sflight.

SELECT * FROM sflight INTO TABLE lt_flights.

DATA ld_field TYPE string VALUE 'CARRID'.

SORT lt_flights BY (ld_field) ASCENDING.
SORT lt_flights BY (ld_field) DESCENDING.

Field name must be uppercase. An empty variable is silently skipped. An invalid name raises a runtime error.


Fully dynamic — both field and direction at runtime — use ABAP_SORTORDER_TAB:

DATA: lt_sort TYPE abap_sortorder_tab,
      lx_sort TYPE abap_sortorder.

lx_sort-name       = 'PRICE'.    " field name, uppercase
lx_sort-descending = abap_true.  " abap_true = 'X', initial = ascending
APPEND lx_sort TO lt_sort.

TRY.
  SORT lt_flights BY (lt_sort).
CATCH cx_sy_dyn_table_ill_comp_val.
  " handle invalid field name
ENDTRY.

Add multiple rows to lt_sort to sort by multiple fields — row order defines priority (first row = primary key). An empty lt_sort leaves the table unsorted.

Don’t set lx_sort-astext = abap_true on numeric or date fields — it forces lexicographic comparison and produces wrong order.