Removing duplicate rows from an internal table in ABAP is a common task. You can implement it using the DELETE ADJACENT DUBLICATES construct, here is an example of ABAP code:
1 |
DELETE ADJACENT DUBLICATES FROM lt_tab. |
With this construct, we will remove all duplicates from the internal table, leaving only unique records. This design is more suitable for internal tables with a small number of fields, where we do not need to remove duplicates for certain fields.
But sometimes the task is to remove duplicates from the table for certain fields. In this scenario, you need to be more careful, because for this task the table must be sorted by the required fields in order for the result to be predictable and correct.
Simple example using DELETE ADJACENT DUBLICATES
Let’s analyze the delete adjacent duplicates ABAP from the internal table using examples. I have created a simple ABAP using the demo table.
1 2 3 4 5 6 7 8 |
DATA lt_sflight TYPE STANDARD TABLE OF sflight. SELECT * INTO TABLE lt_sflight UP TO 20 ROWS FROM sflight. cl_demo_output=>display( lt_sflight ). |
We filled in the internal table and displayed the data on the screen. Although this is a demo table, your data may be different, so I will show my results:

If duplicates in the CARRID and CONNID fields are removed from this table, then the construction will work correctly:
1 |
DELETE ADJACENT DUPLICATES FROM lt_sflight COMPARING carrid connid . |
As a result of performing this removal of duplicates, we get:

Errors in using Example using DELETE ADJACENT DUBLICATES
BUT the construction was executed correctly only because the table records were sorted by these fields initially. Let’s consider another example. How will the program work on the same data, but if they are sorted in a different order:

It can be seen that the data is not sorted by the CARRID and CONNID fields. And if we apply the same construction to such a table, we will get an incorrect result of removing duplicates:

Therefore, for the correct operation of the DELETE ADJACENT DUBLICATES construct, you must first sort the table by these fields using the SORT construct.
Example using DELETE ADJACENT DUBLICATES with SORT
That is, the correct final code of the ABAP duplicate removal program will be as follows:
1 2 3 4 5 6 7 8 9 10 11 12 |
DATA: lt_sflight TYPE STANDARD TABLE OF sflight. SELECT * INTO TABLE lt_sflight UP TO 20 ROWS FROM sflight. SORT lt_sflight BY carrid connid. DELETE ADJACENT DUPLICATES FROM lt_sflight COMPARING carrid connid . cl_demo_output=>display( lt_sflight ). |
In this article, I considered only the main nuance of working with this design, but in the future I will dig even deeper, save it to your favorites.