stratoflow

Retrieving data of an object from another one – tips and tricks

You shouldn’t use SOQL, SOSL and DML operations in loops. It’s very crucial facet because by doing so you can very easily cross the limits of transaction and make your functionality to work only with limited number of objects which could cause all sorts of problems.

By doing so, in the worst case scenario, with SOSL and SOQL, you need to make the search process that depending on fields from other objects.

Building a new application or extending your development team?

🚀 We're here to assist you in accelerating and scaling your business. Send us your inquiry, and we'll schedule a free estimation call.

Estimate your project

Let me show you now a bad example of using SOQL in for loop and ending up with SOQL exception thrown if you have more than 100 accounts:

Id ownerId = // required id 
List <Account> accounts = [Select Id From Account Where User.Id =: ownerId ];
for (Account account : accounts){
Contact contact = [Select Id From Contact Where Contact.Account.ID =: account.ID;
….

}

As you can see, we’ve got a slight problem. In order to make this code functional, without throwing an exception, you need to use loop and add to the list these fields that you want to use in the next SOQL. By doing so we will have every condition field in one list. You alco cannot forget about including field, in the first SOQL, connects both objects (In the following example it is a ContactId).

Id ownerId = // required id 
List <Account> accounts = [Select Id, ContactId From Account Where User.Id =: ownerId ];
List <Id> accountsIDs = new List <Id> ();
for (Account account : accounts){
accountsIDs.add(account.Id);
}

In this situation we can add new SOQL search operation for Contacts:

Id ownerId = // required id 
List <Account> accounts = [Select Id, ContactId From Account Where User.Id =: ownerId ];
List <Id> accountsIDs = new List <Id> ();
for (Account account : accounts){
accountsIDs.add(account.Id);
}
List<Contact> contacts =[Select Id From Contact Where Contact.Account.ID IN: accountsIDs];

This new list of contacts contains every single Contact that would be retrieved in the loop. At this point we need to create new Map. If our objects are triangle by Id then creating Map is fairly simple, because map in Apex get method putAll(List<sObject>) which allow us to put List into Map and key values are automatically assigned and are equal to Id values of the objects in the List.

Id ownerId = // required id 
List <Account> accounts = [Select Id, ContactId From Account Where User.Id =: ownerId ];
List <Id> accountsIDs = new List <Id> ();
for (Account account : accounts){
accountsIDs.add(account.Id);
}
List<Contact> contacts =[Select Id From Contact Where Contact.Account.ID IN: accountsIDs];
Map<Id, Contact> contactsByIds = new Map<Id, sObject>();
contactsByIds.putAll(contacts);

If you don’t want to triangle objects by Ids then you need to create loop to put all objects with custom keys in them. In the first SOQL you must retrieve proper field that will connect both objects.

Id ownerId = // required id 
List <Account> accounts = [Select Id, ContacName From Account Where User.Id =: ownerId ];
List <Id> accountsIDs = new List <Id> ();
for (Account account : accounts){
accountsIDs.add(account.Id);
}
List<Contact> contacts =[Select Id, Name From Contact Where Contact.Account.ID IN: accountsIDs];
Map<String, Contact> contactsByNames = new Map<Id, sObject>();

When everything is ready we can create loop where we will implement required functionality. Contacts will be retrieved from Map by field from iterated object which connect both objects. In the example above it will be a Contact Name and in the example below it is a ContactId.

Id ownerId = // required id 
List <Account> accounts = [Select Id, ContactId From Account Where User.Id =: ownerId ];
List <Id> accountsIDs = new List <Id> ();
for (Account account : accounts){
accountsIDs.add(account.Id);
}
List<Contact> contacts =[Select Id From Contact Where Contact.Account.ID IN: accountsIDs];
Map<Id, Contact> contactsByIds = new Map<Id, sObject>();
contactsByIds.putAll(contacts);

for (Account account : accounts){
Contact contact = contactsByIds.get(account.ContactId ;

To to sum all this stuff up, if we write SOQL query in this way, exception won’t be thrown. As simple as that. I hope my examples will clarify some things and help you out in your personal projects. Good luck!

Building a new application or extending your development team?

🚀 We're here to assist you in accelerating and scaling your business. Send us your inquiry, and we'll schedule a free estimation call.

Estimate your project

Testimonials

The developed software product was built from scratch with solid quality. We have had a long-term engagement with Stratoflow for nearly 10 years. We look at them as partners, rather than contractors. I'm impressed by their team culture and cross-team support.

Nathan Pesin

CTO, Legerity Financials

Stratoflow was a great partner, challenging as well as supporting our customer projects for the best outcome. They have a great pool of talent within the business - all very capability technologists, as well as being business-savvy and suitable for consultancy engagements.

Chris Goodall

Managing Consultant, CG Consultancy (UK) Limited

The bespoke metal exchange platform works great, it is easily accessible and richly functional. Stratoflow managed deadlines capably, meticulously documented their progress, and delivered a complex project at an affordable cost.

Bartlomiej Knichnicki

Vice Chairman, Supervisory Board

We are very pleased with our partnership with Stratoflow and, as we continue to grow, we expect to increase the numbers of developers that work with us on our projects. They have proven to be very skilled and flexible. They're extremely reliable, and they have a very good company culture of their own, which gives them a real edge compared to other providers that serve more as production shops rather than thought partners and creative problem solvers.

Andrew Kennedy

Founder & Managing Director, Tier 2 Consulting

Stratoflow successfully customized the system according to the specific functionalities and without bugs reported. The team was commended for their adaptability in the work process and for their responsiveness.

Joshua Blavins

Tech PM, Digital Agency

The features implemented have received overwhelmingly positive feedback from end-users. Stratoflow has an incredible technical expertise and a high degree of flexibility when it comes to changing project requirements.

Adam Hill

Chief Technology Officer, Legerity

They have impressively good knowledge of AI issues. Very responsive to any amendments and findings. Very good communication. We received a finished project which could be implemented into production shortly after testing.

CO-Founder & CTO

Circular Fashion Company

They provided superb service with seamless communication and a highly professional, technical approach. The team displays impressive technical expertise and are willing to share information and engage in constructive feedback.

Filip Stachnik

Operations Manager, Otwarte Klatki (part of Anima International)

They're very skilled technically and are also able to see the bigger picture. Stratoflow can actually think about solutions, not just the technical task at hand, which they've been assigned.

Arnd Jan Prause

Chief Operating Officer, musQueteer

Stratoflow delivered the website successfully within the timeframe and budget. They assured that the output met the set requirements. Overall, the team's performance was excellent and recommended for their exceptional technical business expertise. They've been able to deliver all of their work on time and within budget, which has been very impressive.

Lars Andersen

Founder & CEO, My Nametags

Travel sector rebound after the pandemic is complete. We have fantastic global coverage of travel data distribution due to mutual agreements and data exchange between aggregators. Competition for the best price of limited resources degradates margins.

How to win? Provide personalized experience and build your own products in the front-office. The missing bits: a traveller golden record collecting past activities and a AI/ML recommendation technology.

Michał Głomba

CEO at Stratoflow