Sub topic 10
Polymorphic relationships and TYPEOF
This chapter covers relationship fields that can point to more than one object type. It assumes you can write child-to-parent queries with dot notation, such as Account.Name on a Contact. It also assumes you know relationship names and basic Apex syntax. Apex is needed for the last section.
What a polymorphic relationship is
Most lookup fields point to exactly one object. Contact.AccountId always references an Account, so Account.Name always resolves to the same set of fields.
A polymorphic relationship field can reference records from several objects. The ID field holds the record ID. The relationship field is the traversable path to the record, and the ID's key prefix tells Salesforce which object it belongs to.
The common polymorphic fields are:
| Object | Relationship field | Can point to |
|---|---|---|
| Task, Event | `What` (ID field `WhatId`) | Account, Opportunity, Case, Campaign, custom objects, and others |
| Task, Event | `Who` (ID field `WhoId`) | Contact or Lead |
| Lead, Case | `Owner` (ID field `OwnerId`) | User or Group (a queue is a Group) |
| Note, Attachment | `Parent` (ID field `ParentId`) | Several object types |
Not every Owner field is polymorphic. On Account, Contact, and Opportunity, Owner points only to User, so it behaves like any other parent lookup. It is polymorphic on objects that support queue ownership, such as Lead and Case.
The Task and Event What and Who fields are the usual way to see this. A single Event can be attached to an Account, and the next Event in the same table can be attached to an Opportunity.
Querying the fields every type shares
Without TYPEOF, you can read only fields that exist on every possible target. Two are always available:
Name, which exists on the target objects through the shared Name data.Type, which holds the API name of the object the record belongs to, such asAccountorOpportunity.
SELECT Id, Subject, What.Type, What.Name
FROM Task
WHERE WhatId != null
ORDER BY What.TypeThis query returns one row per Task, with the parent's object type and name. It works whether the parent is an Account, an Opportunity, or a custom object.
You can also filter on these fields:
SELECT Id, Subject, What.Name
FROM Event
WHERE What.Type = 'Account'Use this to narrow results to one target type. For Lead and Case ownership, the same idea separates queue-owned records from user-owned ones:
SELECT Id, Status, Owner.Name, Owner.Type
FROM Case
WHERE Owner.Type = 'Queue'Owner.Type returns User or Queue here, because a queue is stored as a Group record and reported as Queue.
Dot notation with a type-specific field fails on a polymorphic path. What.Phone is invalid because Opportunity has no Phone field. What.Account.Name is invalid for the same reason, because the path does not know which object it is walking through. You have to use TYPEOF.
TYPEOF: type-specific fields per target
TYPEOF lets you list a different set of fields for each possible target type. It goes in the SELECT list.
SELECT Id, Subject,
TYPEOF What
WHEN Account THEN Name, Phone
WHEN Opportunity THEN Name, Amount
END
FROM EventRead it as a switch statement:
TYPEOF Whatnames the polymorphic relationship field to inspect.- Each
WHEN <ObjectName> THEN <fields>branch applies when the record is of that type. ENDcloses the clause.
For an Event that points to an Account, the result includes Name and Phone. For one that points to an Opportunity, it includes Name and Amount. For any other type, no What fields come back, unless you add an ELSE branch.
The ELSE branch
ELSE covers every target type that has no WHEN branch of its own. It can list only fields that all those types share.
SELECT Id, Subject,
TYPEOF What
WHEN Account THEN Phone
WHEN Opportunity THEN Amount
ELSE Name
END
FROM EventHere Accounts return Phone, Opportunities return Amount, and everything else (Cases, Campaigns, custom objects) returns Name.
TYPEOF on Owner
Owner on a Lead works the same way. User and Group have different fields, so each gets its own branch:
SELECT Id, Company,
TYPEOF Owner
WHEN User THEN Username, Email
WHEN Group THEN DeveloperName
END
FROM LeadUse the object name in WHEN. For queues, that name is Group, not Queue. The word Queue appears only as a value of the Type field.
Rules to remember
- TYPEOF belongs in the SELECT list only. You cannot use it in WHERE, ORDER BY, or GROUP BY.
- To filter on the target type, use
What.Typein the WHERE clause. To filter on a field of one specific type, you can write the filter through the path, such asWhat.Name LIKE 'Acme%'. That works becauseNameis a shared field. - Each field in a THEN list must exist on that object. A typo or a field from the wrong object is a query error, not an empty column.
- If you do not list a type and have no ELSE, records of that type still come back, but the relationship field contains no data for them.
Combining a type filter with TYPEOF
In practice you often want both: only the types you handle, and the right fields for each.
SELECT Id, Subject,
TYPEOF What
WHEN Account THEN Name, Phone
WHEN Opportunity THEN Name, Amount
END
FROM Event
WHERE What.Type IN ('Account', 'Opportunity')
AND ActivityDate = THIS_MONTH
ORDER BY ActivityDateThe WHERE clause trims the rows. TYPEOF shapes the columns. Every returned row matches one of the two branches.
Reading polymorphic results in Apex
In Apex, the polymorphic field is typed as a generic SObject. After a TYPEOF query, the value is an instance of the concrete type, so you check with instanceof and cast.
List<Event> events = [
SELECT Id, Subject,
TYPEOF What
WHEN Account THEN Name, Phone
WHEN Opportunity THEN Name, Amount
END
FROM Event
WHERE What.Type IN ('Account', 'Opportunity')
LIMIT 20
];
for (Event e : events) {
if (e.What instanceof Account) {
Account a = (Account) e.What;
System.debug(e.Subject + ' -> Account ' + a.Name + ', phone ' + a.Phone);
} else if (e.What instanceof Opportunity) {
Opportunity o = (Opportunity) e.What;
System.debug(e.Subject + ' -> Opportunity ' + o.Name + ', amount ' + o.Amount);
}
}Three points about this code:
e.What instanceof Accountis false whenWhatis null, so the null case is covered by the same check. Events with no related record do not throw.- Only the fields in the matching THEN list are populated on the cast object. Reading
a.Industryhere throws an exception, because the query did not select it. - If you need the type without casting,
e.WhatId.getSObjectType()returns theSObjectTypefor the ID. It works even when the query did not select the relationship at all.
Event e = [SELECT Id, WhatId FROM Event WHERE WhatId != null LIMIT 1];
Schema.SObjectType targetType = e.WhatId.getSObjectType();
System.debug(targetType); // for example: AccountFor the shared-fields form, What.Type and What.Name are read through the generic object:
Task t = [SELECT Id, What.Type, What.Name FROM Task WHERE WhatId != null LIMIT 1];
System.debug(t.What.get('Name'));Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Querying `What.Phone` directly | Query error: the field does not exist on every target | Use `TYPEOF What WHEN Account THEN Phone END` |
| Using `WHEN Queue` for queue owners | Error: Queue is not an object in this context | Use `WHEN Group` |
| Expecting TYPEOF to filter rows | Unmatched types still come back | Add `WHERE What.Type IN (...)` |
| Casting without `instanceof` | `TypeException` when the record is another type | Check the type first, or switch on `getSObjectType()` |
| Reading an unselected field after the cast | `SObjectException` | Add the field to the matching THEN list |
| Using TYPEOF in WHERE or ORDER BY | Query error | Filter with `.Type`, sort on shared fields |
Exercises
Exercise
You run SELECT Id, What.Phone FROM Task and get an error. Why does it fail, and how do you rewrite it to return Phone for Tasks related to an Account?
Show answer
What is polymorphic, so a path through it can only use fields shared by every possible target, and Phone is not one of them (Opportunity has no Phone field). Rewrite it with TYPEOF: SELECT Id, TYPEOF What WHEN Account THEN Phone END FROM Task. Add WHERE What.Type = 'Account' if you want only the Account-related Tasks.
Exercise
Write a query that returns each Lead's Id and Company. For leads owned by a user it should include the owner's Username, and for leads owned by a queue it should include the queue's DeveloperName.
Show answer
SELECT Id, Company, TYPEOF Owner WHEN User THEN Username WHEN Group THEN DeveloperName END FROM Lead
Exercise
In Apex, a loop over Events reads ((Account) e.What).Name and sometimes throws a TypeException. What is the cause and the fix?
Show answer
Some Events point to a different object, such as an Opportunity, and the cast to Account fails for them. Guard the cast with if (e.What instanceof Account), and add else if branches for the other types you expect. The instanceof check is also false when What is null, so it covers unrelated Events too.