Newer Version Available
Working with Polymorphic Relationships in SOQL Queries
A polymorphic relationship is a relationship between objects where a referenced object
can be one of several different types. For example, the What relationship
field of an Event could be an Account, a Campaign, or an Opportunity.
The following describes how to use SOQL queries with polymorphic relationships in Apex. If you want more general information on polymorphic relationships, see Understanding Polymorphic Keys and Relationships in the Force.com SOQL and SOSL Reference.
You can use SOQL queries that reference polymorphic fields in Apex to get results that depend on
the object type referenced by the polymorphic field. One approach is to filter your
results using the Type qualifier. This example queries Events that
are related to an Account or Opportunity via the What
field.
Another
approach would be to use the TYPEOF clause in the
SOQL SELECT statement. This example also queries
Events that are related to an Account or Opportunity via the What
field.
These queries will return a list of sObjects where the relationship field references
the desired object types.
If you need to access the referenced object in a polymorphic relationship, you can use the instanceof keyword to
determine the object type. The following example uses instanceof to determine whether an Account or Opportunity is related to an
Event.
Note
that you must assign the referenced sObject that the query returns to a variable of the
appropriate type before you can pass it to another method. The following example queries
for User or Group owners of Merchandise__c custom objects using a SOQL query with a
TYPEOF clause, uses instanceof to determine the owner type, and then
assigns the owner objects to User or Group type variables before passing them to utility
methods.