Newer Version Available

This content describes an older version of this product. View Latest

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 Who relationship field of a Task can be a Contact or a Lead.

The following describes how to use SOQL queries with polymorphic relationships in Apex. If you want more general information on polymorphic relationships, see Understanding Relationship Fields and Polymorphic Fields in the 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 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
  1. Queries for User or Group owners of Merchandise__c custom objects using a SOQL query with a TYPEOF clause
  2. Uses instanceof to determine the owner type
  3. Assigns the owner objects to User or Group type variables before passing them to utility methods