Soql for list of id until result

apexforsoql

So i have list id and query soql until I get the result. It looks like that, i want to query that soql for each id until i get result. It doesn't work good, but no error. FieldId__c is id from another object.

List<String> ids = new List<String>(); //just for example, i am getting id with method.
for (String id : ids) {
    Object__c objList = [SELECT Id FROM Object__c WHERE field__c = 'something'  and FieldId__c = :id];
    if (objList.id != null) break;
}

Best Answer

According to updated question with details, you can make one SOQL query with IN:

List<String> ids = new List<String>(); 
List<Object__c> objList = [SELECT Id FROM Object__c WHERE field__c = 'something' AND FieldId__c IN :ids];
if (objList.size() > 0) {
    //it is the same as breaking from for-loop
}
    

You can also make a map that matches initial Id with retrieved Object__c, if you need it later:

Map<Id, Object__c> m = new Map<Id, Object__c>();
for (Object__c o : [SELECT Id, FieldId__c FROM Object__c WHERE field__c = 'something' AND FieldId__c IN :ids]) {
    m.put(o.FieldId__c, o);
}
Related Topic