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

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

  1. Hi Luke,
    thanks for the blog post, I certainly learned an item or two on my journey of learning how I can SOQL query Accounts that do not have a contact, in the related list, that is not marked “Yes” in our picklist field called “Primary Contact”
    Phrased another way… I’m trying to locate Accounts that do not have a Primary Contact identified so we can work just those Accounts.

    Would you happen to have any insights? Thanks!

    1. Hey Chris,

      Sorry for the late reply. That should be possible with a “semi-join” clause. Something like this:

      Select Id,
      from Account
      where Id not in (Select AccountId
      from Contact
      where Primary_Contact__c = ‘Yes’)

  2. My Description/comments in Task object have about 30000 characters when pulled in soql shows null values or the column doesn’t display, please help

Leave a Reply

Your email address will not be published.