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
TYPEOFkeyword followed by the polymorphic field name in your
- List each possible object type and the corresponding fields you want to retrieve for each.
ELSEto specify a default set of fields for any unexpected types.
WHEN Account THEN Industry, BillingStreet
WHEN Opportunity THEN Amount, CloseDate
This query returns:
- For Accounts:
- For Opportunities:
- For anything else:
References & Useful URLs
- SOQL & SOSL Reference – TYPEOF