0

I have some List with values and i need to get record from sobject for each element from that list. So it looks like that. But its very close to limitations. Any ideas gow to do it? Its necessary to check every element from list so IN is not enough. I need to get one element from Object for each element from list, when IN gives me all elements. So if i need one record for each element in list i can select all and after it via adding to map and check if id already in map?

for( String element: list) {
 Select id  from Object Where  field = (Select field2 from Object2 where id = element)
}

2 Answers 2

1

Let's say, that you have in list list of sobjects with populated Id field, or you have some prepared values to filter records by. You can do this query, not in the loop. In this case, your SOQL query will look like:

SELECT Id
FROM Object__c
WHERE Field__c IN (
    SELECT Field2__c
    FROM Object2__c
    WHERE Id IN :list
)

this part of the SOQL is called "single-level nested query"

(
    SELECT Field2__c
    FROM Object2__c
    WHERE Id IN :list
)
1
  • I need get one element for each element in list. So one for 0, one for 1 and so on. In doesnt work right in my case, also i will edit with some idea.
    – jeltaboknu
    Commented Sep 15, 2021 at 10:56
0

You can use Map for this.

List<string> names = New List<String>{'Orient','Smokey'};
Map<string, Contact> contacts = new Map<string, Contact>();
// populate map with NULLs, so that map have NULL for list element, if no record
for(String str : names){
       contacts.put(str, null);
 }
// repopulate with actual data
for(Contact con : [Select Id, FirstName From Contact Where FirstName =:names ]){
    contacts.put(con.FirstName, con);
}

You must log in to answer this question.

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