Preface – This post is part of the Write Your First Intermediate Trigger series.
Now that you know combining Apex with SOQL is the secret sauce to mastering triggers, let’s learn exactly how to do this!
First off, know that the output of every SOQL query is an Apex list. However, we want to take this one step further. We want to inject Apex directly into the SOQL query itself!
Salesforce knows you’re using a bind variable when you precede your Apex variable with a colon (:) – here’s an example:
String myFamilyName = 'Liu'; List<Contact> myFamily = [SELECT FirstName, Best_Friend__c FROM ContactWHERE LastName = :myFamilyName];
Don’t forget the colon (:), it’s small but it’s the most important part!
Now, why use a bind variable when we could’ve simply done LastName = ‘Liu’ instead?
The reason is we don’t always know what the value of our bind variables are! Here’s another example that should make this more obvious:
String familyFriendId = myFamily.Best_Friend__c;List<Contact> friendsOfFriend = [SELECT FirstName, LastName FROM ContactWHERE Best_Friend__c = :familyFriendId];
See what we did there?
First, we used an index to get the first member of my family. Then, we used dot notation to get the ID of the Best Friend of this family member (“Best Friend” is a lookup field to the Contact object). Finally, in our SOQL query, we used a bind variable to find every other contact in our database that has the same best friend!
We could’ve repeated this with a loop through all of my family members if we wanted to, querying all family friends of friends… aka my third degree connections! LinkedIn… your days are numbered!