How to Use TYPEOF in SOQL Query for Polymorphic Fields

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!


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:

  1. Use the TYPEOF keyword followed by the polymorphic field name in your SELECT clause.
  2. List each possible object type and the corresponding fields you want to retrieve for each.
  3. Use ELSE to specify a default set of fields for any unexpected types.


  WHEN Account THEN Industry, BillingStreet
  WHEN Opportunity THEN Amount, CloseDate
  ELSE Name
FROM Event

This query returns:

  • For Accounts: IdIndustry, and BillingStreet
  • For Opportunities: IdAmount, and CloseDate
  • For anything else: IdName

References & Useful URLs

  • SOQL & SOSL Reference – TYPEOF

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top
Introducing All Access Pass