Search code examples
performancesalesforcesoql

Salesforce SOQL query length and efficiency


I am trying to solve a problem of deleting only rows matching two criteria, each being a list of ids. Now these Ids are in pairs, if the item to be deleted has one, it must have the second one in the pair, so just using two in clauses will not work. I have come up with two solutions.

1) Use the two in clauses but then loop over the items and check that the two ids in question appear in the correct pairing.

I.E.

for(Object__c obj : [SELECT Id FROM Object__c WHERE Relation1__c in :idlist1 AND Relation2__c in:idlist2]){
    if(preConstructedPairingsAsString.contains(''+obj.Relation1__c+obj.Relation2__c)){
        listToDelete.add(obj);
    }
}

2) Loop over the ids and build an admittedly long query.

I like the second choice because I only get the items I need and can just throw the list into delete but I know that salesforce has hangups with SOQL queries. Is there a penalty to the second option? Is it better to build and query off a long string or to get more objects than necessary and filter?


Solution

  • In general you want to put as much logic as you can into soql queries because that won't use any script statements and they execute faster than your code. However, there is a 10k character limit on soql queries (can be raised to 20k) so based on my back of the envelope calculations you'd only be able to put in 250 id pairs or so before hitting that limit.

    I would go with option 1 or if you really care about efficiency you can create a formula field on the object that pairs the ids and filter on that.

    formula: relation1__c + '-' + relation2__c
    
    for(list<Object__c> objs : [SELECT Id FROM Object__c WHERE formula__c in :idpairs]){
        delete objs;
    }