In certain cases, you might need to sort an internal table in ascending & descending order both based on certain columns to achieve a particular output. SAP has already provided the solution quiet before. I am writing this blog post as I have come across a similar situation a few days back.


First of all, we should check the syntax of the SORT. Then a lit bit of theory.

SORT <itab> [<order>] [AS TEXT]
[BY <f1> [<order>] [AS TEXT]... <fn> [<order>] [AS TEXT]].


If the BY option is not used then, the internal table <itab> will be sorted by its standard key.

To define a different sort key, use the BY option. The system then sorts the dataset according to the specified components <f 1 >… <f n >. These fields can be of any type, including type P, I, and F fields, or tables. The options that you specify behind individual fields overwrite for these fields the options specified before BY.

If a sort criterion is not known until runtime, you can set it dynamically by writing (<name>) instead of <f i >. The field <name> contains the name of the sort key field. If <name> is empty at runtime, the system ignores it. If it contains an invalid component name, a runtime error occurs.

You can specify the sorting sequence by using DESCENDING or ASCENDING in the <order> option. The default is ascending.

Without the option AS TEXT, the system sorts character fields binarily and according to their platform-dependent internal coding. With the option AS TEXT, the system sorts character fields alphabetically according to the current text environment.

Stable keyword

It allows you to perform a stable sort, that is, the relative sequence of lines that are unchanged by the sort is not changed. If you do not use the STABLE option, the sort sequence is not preserved. If you sort a table several times by the same key, the sequence of the table entries will change in each sort. However, a stable sort takes longer than an unstable sort.

Now, please check the lines of code below for further reference.


Before sort

After sort


That’s it. ?

If you like this blog post, please like, share & comment.

Also, please don’t forget to endorse me on LinkedIn. ?

jooman neshat


Author Since: April 23, 2021

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x