Query Activity Related To Fields With SOQL

Salesforce Activity records have special polymorphic relationship fields that allow them to be linked to various objects all from one field. For example, the Related To field also known as the “WhatId”, one of the worst named things I’ve ever come across, can be linked to any object that allows activities. One challenge has been querying the parent related to’s fields besides its Id & Name because it could refer to different parent objects and Salesforce couldn’t guarantee if it would exist or not depending on the records selected.

Invalid Account Related To SOQL Example

The following example queries task records related to accounts and tries to query the related account’s billing state but this isn’t allowed with this syntax.

Valid Account Related To SOQL Example

The following SOQL query using the “TypeOf” operator is how one can select the account’s related to fields. This is new as of Summer 19 (version 46). TypeOf SOQL Documentation

Workbench Execution

Accessing Related To Fields In Apex

One can’t access the polymorphic fields directly in Apex. The compiler doesn’t allow it. It only allows the Id and Name to be accessed directly. However, one can indirectly access the fields using the get function on the related record.


  • No Bulk API Support – This limits the ability for one to generate an export for a data conversion if needed for large data volumes.
  • Limited Tool Support – As of September 2019, Workbench seems to be the best tool for this feature. The Developer Console’s query feature doesn’t seem to work with it and the SFDX query command doesn’t either.
  • No Direct Field Access In Apex. After querying the related to fields, one can’t access “What.BillingState” directly for example. The apex compiler complains. One has to indirectly access it with “What.get(‘BillingState’)”.
  • No semi-join TypeOf Support.
  • See TypeOf SOQL Documentation for other limitations

2 thoughts on “Query Activity Related To Fields With SOQL”

Leave a Reply

Your email address will not be published. Required fields are marked *