cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

How sorting works in an internal table in given case??

ABAPer_1631
Explorer
0 Kudos
172

Hello,

I know this would be basic question, but I need this to figure-out issue. I have an internal table lt_result with four fields (field1, field2, field3, field4). I have fetched data from an Infotype into this internal table. Now, I have N no.of records in lt_result. Among these, I have two records with same value in field2 where field4 is varied.

EG: Before SORT

field1field2field3field4
1234501.01.201301.01.201301.04.2012
1234504.11.202004.11.202004.11.2020
1234520.12.202220.12.202201.04.2012
1234520.12.202220.12.202204.11.2020

I would like to sort with field1 ascending and field2 descending.

SORT lt_result BY <field1> ASCENDING <field2> DESCENDING.

In that case, what will happen if for the records in violet.

i) which record will come first either 01.04.2012 or 04.11.2020?

ii) usually how does sorting works for date comparison?

Thanks!!

View Entire Topic
Dennis_Suck85
Participant
0 Kudos

Dear ABAPer_1631,

When you execute this sort command SORT lt_result BY field1 ASCENDING field2 DESCENDING you'll get a follow Table:

Dennis_Suck85_0-1747480248601.png

Primary key: field1 (ASCENDING)
- All rows have field1 = 12345
- Since every value is identical, the order remains unchanged

Secondary key: field2 (DESCENDING)
- Date fields (TYPE D) are stored internally as an integer in the format YYYYMMDD
- With DESCENDING, the comparison is lexicographic/numeric 'backwards' (newer dates (larger numbers) come before older dates (smaller numbers)).

Stable sort for identical keys
- If two records share the same values in field1 and field2, their original insertion order is preserved.

i) Which record appears first: 01.04.2012 or 04.11.2020?
- Both entries actually share field2 = 20.12.2022.
- The sort criteria are exhausted, so they remain in their original order:
○ Record with field4 = 01.04.2012 (originally row 3)
○ Record with field4 = 04.11.2020 (originally row 4)
-> 01.04.2012 appears before 04.11.2020.


ii) How does the date comparison work?
- Date fields (TYPE D) are stored internally in the format YYYYMMDD.
- Compared lexicographically/numerically For DESCENDING: 20221220 > 20201104 > 20130101 > 20120401

-> Newest dates end up at the top.
I hope my explanation has provided some clarity.

Best regards,
Dennis