Introduction
In Salesforce, activities (Tasks and Events) use two special polymorphic lookup fields — WhoId
and WhatId
— to relate records to people and business objects. Understanding these fields is essential for reporting, querying, and writing Apex that works with Tasks and Events.
What is WhoId?
WhoId
is a polymorphic lookup on Task and Event that points to a record representing a person. The WhoId can reference either the Contact
or the Lead
object. Use WhoId when the activity is related to an individual person.
What is WhatId?
WhatId
is a polymorphic lookup on Task and Event that points to a record representing a business object. The WhatId can reference objects like Account
, Opportunity
, Case
, Campaign
, custom objects, and more. Use WhatId when the activity is related to an account, opportunity, or other non-person entity.
Key Characteristics
– Both fields are polymorphic lookup fields (they accept multiple sObject types).
– They are available on both Task
and Event
.
– An activity can have one or both fields populated — e.g., a meeting with a contact about an opportunity (WhoId = Contact, WhatId = Opportunity).
SOQL and Polymorphic Fields
When querying polymorphic fields in SOQL, you can use TYPEOF (API version 30.0+) to handle different types, or use getSObject()
in Apex to dynamically access the referenced record.
// Example SOQL using TYPEOF
SELECT Id, Subject, WhoId, WhatId,
TYPEOF WhoId WHEN Contact THEN Name, Email WHEN Lead THEN Name, Company END
FROM Task
WHERE WhoId != null
Apex examples
Accessing the polymorphic reference in Apex:
// Using getSObject() and instanceof
Task t = [SELECT Id, WhoId, WhatId FROM Task LIMIT 1];
SObject who = t.getSObject('WhoId');
if (who instanceof Contact) {
Contact c = (Contact) who;
System.debug('Contact name: ' + c.Name);
} else if (who instanceof Lead) {
Lead l = (Lead) who;
System.debug('Lead company: ' + l.Company);
}
Common Use Cases
– Relate a Task to a Contact (WhoId) and an Opportunity (WhatId).
– Use reports to show activities by Contact or by Account depending on which field is used.
– Trigger logic that needs to behave differently when WhoId points to a Lead vs Contact.
Limitations & Best Practices
– Polymorphic fields cannot be used in certain cross-object formulas.
– In validation rules and workflow rules, check the WhoId
or WhatId
prefix (e.g., LEFT(WhoId,3)
) is not reliable. Prefer checking related record types in Apex or use custom fields when strict relationships are required.
– When building integrations, be explicit about the sObject type you expect for WhoId/WhatId to avoid runtime errors.
Short Summary
WhoId
links an activity to a person (Contact or Lead). WhatId
links an activity to a business object (Account, Opportunity, Case, custom objects, etc.). Both are polymorphic fields on Task and Event used to model relationships between activities and other records in Salesforce.
Leave a Reply