Polymorphic relationships in Salesforce offer flexibility by connecting records to various object types. Like you can use “WhatId” on Task & Event objects to link tasks and events to different standard and custom objects.
But querying these relationships can be tricky. Enter the TYPEOF keyword – your best friend for dynamic SOQL queries!
What Is TYPEOF?
TYPEOF lets you choose specific fields to select based on the runtime type of records in a polymorphic relationship. This allows for cleaner, more efficient queries.
Here’s how it works:
- Use the
TYPEOF
keyword followed by the polymorphic field name in yourSELECT
clause. - List each possible object type and the corresponding fields you want to retrieve for each.
- Use
ELSE
to specify a default set of fields for any unexpected types.
Example:
SELECT Id,
TYPEOF What
WHEN Account THEN Industry, BillingStreet
WHEN Opportunity THEN Amount, CloseDate
ELSE Name
FROM Event
This query returns:
- For Accounts:
Id
,Industry
, andBillingStreet
- For Opportunities:
Id
,Amount
, andCloseDate
- For anything else:
Id
,Name
References & Useful URLs
- SOQL & SOSL Reference – TYPEOF