I have a use case where in 1 Order Contains multiple OrderItems, and these orderitems contains records. lets say there are 5 orderitems to 1 order, and among 5 orderitems 2 are duplicate and 3 are unique, so my question is how do i remove these 2 duplicates and how should i compare the list of 5 orderitems with each other to delete it.

Here is my code.


Map<Id,Order> ord = new Map<Id,Order>([Select id from Order LIMIT 50]);
Set<Id> ordId = new Set<Id>();
Set<Id> ordId1 = new Set<Id>();
Set<Id> ordId2 = new Set<Id>();
Set<Id> ordId3 = new Set<Id>();
Set<Decimal> ordId4 = new Set<Decimal>();
Set<Decimal> ordId5 = new Set<Decimal>();
Set<Number> ordId6 = new Set<Number>();
for(Order o : ord.values())
List<OrderItem> ordListItem = [Select OrderId,ebMobile__Product2__c,Product2Id,ebMobile__ErpProductCode__c,ListPrice,UnitPrice,Quantity,
                              AvailableQuantity,ebMobile__UOMCode__c,ebMobile__ReceivedQuantity__c From OrderItem where OrderId =: o.Id];

    for(OrderItem items : ordListItem)
    if(ordId4.contains(items.ListPrice) && ordId5.contains(items.UnitPrice) && ordId6.contains(Quantity))




1 Answer 1


If you want to compare sObjects, add them in Set with the fields you want to be compared (without Id, because it is always unique sObject.clone()). (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_set_sobject.htm)

Then gather all ids that wasn't successfully added to the Set and remove these orderItems.

List<OrderItem> items = [
        SELECT OrderId,ebMobile__Product2__c,Product2Id,ebMobile__ErpProductCode__c,ListPrice,UnitPrice,Quantity,
        FROM OrderItem
        WHERE OrderId = :o.Id

Set<OrderItem> uniqueItems = new Set<OrderItem>();
List<Id> itemsIdsToRemove = new List<Id>();
for (Integer i = 0; i < items.size(); i++) {
    OrderItem toCheck = items[i].clone(false);
    if (!uniqueItems.add(toCheck)) {

List<OrderItem> toRemove = [SELECT Id FROM OrderItem WHERE Id IN :itemsIdsToRemove];

delete toRemove;


I strongly recommend you to NOT use SOQL within for-loop. Gather orderIds in List and make selection with OrderId IN: orderIds where-statement.

  • 4
    Actually there is no need to run a query just for deletion since you already have the list of ID. List<OrderItem> itemsToRemove = new List<OrderItem >(); for (Integer i = 0; i < items.size(); i++) { OrderItem toCheck = items[i].clone(false); if (!uniqueItems.add(toCheck)) { itemsToRemove.add(new OrderItem(items[i].Id)); } } delete(itemsToRemove); Commented Dec 14, 2019 at 14:23
  • @Mariia Hats off to you, honestly thank you, you have saved my lot of time it has solved my problem.
    – vishal
    Commented Dec 14, 2019 at 19:47
  • @HengkyIlawan thanks for your value time and for the response even your strategy is correct. thank you so much.
    – vishal
    Commented Dec 14, 2019 at 19:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .