Problem: I have an external service bulk inserting a task and including a foreign key to my table business. The service will be creating ~100-500 tasks at a time.

I'm trying to build a bulkified trigger to perform a SOQL via the foreign key and then insert the correct id into the Task Related To/WhatId.


Task.Id: 00T54000007VTUOEA4
Task.WhatId: <null>
Task.BusinessUUID__c: 123e4567-e89b-12d3-a456-426655440000

Business__c.Id: a1m54000001uQZpAAM
Business__c.Business_UUID__c: 123e4567-e89b-12d3-a456-426655440000

On insert of Task where:

iter = [select id,BusinessUUID__c from Task]

biz = [select id from Business where Business_UUID__c = :iter.BusinessUUID__c]

Update Task.WhatId with biz.id

Obviously, I'm trying to avoid calling the soql's above within a for loop so currently I'm considering assigning the entire business object to a map?

1 Answer 1


You'll want to adopt what we might call the collect-query-update pattern.

First, you iterate over records that contain some attribute by which you wish to query and accumulate the values of that attribute:

Set<String> businessUUIDs = new Set<String>();

for (Task t: Trigger.new) {
    if (t.Business_UUID__c != null) {

Then, you perform a query limited to just the parent objects you want. Typically, you'll want to turn this into a Map keyed on the attribute you're interested in:

Map<String, Business__c> businessMap = new Map<String, Business__c>();
for (Business__c b : [SELECT Id, Business_UUID__c FROM Business__c WHERE Business_UUID__c IN :businessUUIDs]) {
    businessMap.put(b.Business_UUID__c, b.Id);

(There's a one-liner for doing this by (ab)using query aliasing; I tend to prefer this explicit implementation for clarity).

And finally you iterate back over the initial records and update based on what you got in your Map:

for (Task t: Trigger.new) {
    if (businessMap.containsKey(t.Business_UUID__c)) {
        t.WhatId = businessMap.get(t.Business_UUID__c);

(Assuming this is a before insert trigger).

There's some level of variation and elaboration possible here: what do you do if there are duplicate Business Ids on Businesses? What if a Task's Business Id is not found? and so forth. But the core pattern remains the same.

You must log in to answer this question.

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