Polymorphic Relationships in Salesforce SOQL (Complete Guide with Examples)

In Salesforce, relationships between objects are very important because they help us connect data across different objects, such as Account, Contact, Opportunity, and more.

Normally, we use relationships like lookup or master-detail where one field connects to only one object type. However, in some real-world scenarios, we need more flexibility.

For example, a Task can be related to either a Contact or a Lead. In such cases, Salesforce provides something called polymorphic relationships.

In Salesforce, we have various types of relationships, including child-to-parent, parent-to-child, master-detail, and lookup. There are some scenarios where we require a deeper level of flexibility in the object relationships.

In this situation, we require polymorphic relationships that allow a child object to reference multiple parent objects of different types.

In this article, you will learn everything about polymorphic relationships in Salesforce SOQL. We will cover definitions, examples, queries, real-world use cases, and best practices so you can understand this concept clearly and apply it to real projects.

What is a Polymorphic Relationship in Salesforce?

In Salesforce SOQL, polymorphic relationships refer to relationships where a single relationship field can reference multiple object types.

  • One field → Multiple possible parent objects

For example:

  • A Task can be linked to a Contact or a Lead
  • An Event can be linked to an Account or an Opportunity

This flexibility helps developers handle different scenarios without creating multiple fields.

These are typically seen in standard objects, such as Task and Event, where fields like WhoId and WhatId can refer to multiple object types.

In Salesforce, polymorphic relationships are predefined and cannot be created for custom objects.

Examples of Polymorphic fields:

  • WhoId – This field can refer to either a contact or a lead.
  • WhatId – This field can reference objects such as AccountOpportunityCase, or a custom object.

Why Polymorphic Relationships are Important

Polymorphic relationships are important because:

  • They reduce the need for multiple lookup fields
  • They make data modeling flexible
  • They support real-world business scenarios
  • They simplify activity tracking

Without polymorphic relationships, developers would need multiple fields and complex logic.

Polymorphic Relationships in Salesforce SOQL

While querying the polymorphic fields in SOQL, the type of the referenced object is not directly specified in the field name.

Instead, we use the TYPEOF clause to determine the referenced object’s type and extract the relevant fields.

Syntax of querying the Polymorphic fields in SOQL:

SELECT fieldList
        TYPEOF typeOfField
            WHEN whenObjectType THEN whenFieldList [...]
            ELSE elseFieldList
        END
FROM objectType

In the above SOQL query syntax, the TYPEOF clause enables us to branch the query logic based on the parent object’s type.

Example of querying Polymorphic fields:

Let’s take an example where we execute a SOQL query to retrieve information about Tasks whose WhoId field could refer to a Lead or Contact.

SELECT Id, Status, Subject, TYPEOF who
                        WHEN Contact THEN Name
                        WHEN Lead THEN Name, Phone
                        END
FROM Task

Output:

Polymorphic Relationships in Salesforce SOQL

In the above query, the TYPEOF keyword is used to determine the type of value based on the field being used.

Along with the TYPEOF, we have also used the who keyword to check if the WhoId is  Contact, then it will return Name, and when the WhoId is related to a lead, it will return Name and Phone.

Use case example of Polymorphic queries in Salesforce SOQL

Let’s take a real-time example where we will execute the SOQL with polymorphic functionality using the TYPEOF keyword.

List<Task> taskList = [SELECT Id, Status, Subject, TYPEOF who
							WHEN Contact THEN Name
							WHEN Lead THEN Name, Phone
							END
FROM Task];
for(Task task : taskList) {
	if(task.Who instanceof Contact) {
		Contact con = task.Who;
		System.debug('Task Id: ' + task.Id + ' related to Contact Name' +con.Name);
	}else if(task.who instanceof Lead) {
		Lead lead = task.who;
		System.debug('Task Id ' + task.Id +' related to Lead Name ' + lead.Name);
	}
}

Output:

Salesforce Polymorphic queries using TYPEOF

After executing the above query, we got the output as the Contact Name because the Whoid in the task was referred to the contact.

In the above SOQL query, applying the principle of polymorphism, we added a condition: if the ‘whoid’ object is a contact, retrieve the contact name; otherwise. It will return the Lead name.

Polymorphic Relationship Queries using TYPE Qualifier

In SOQL, by using the TYPE qualifier, we can reference polymorphic fields in Apex to get results that depend on the object type referenced by the polymorphic field.

In the SOQL query below, we will return events related to an account or opportunity via the ‘What’ field.

List<Event> events = [SELECT Description FROM Event WHERE What.Type IN ('Account', 'Opportunity')];

Output:

Polymorphic Relationships in Salesforce SOQL using TYPE

This way, you can query the records using the TYPE keyword in the polymorphic SOQL queries.


Polymorphic Relationship Queries using the instanceOf keyword

When accessing the referenced object in a polymorphic relationship, you can use the instanceOf keyword to determine the object type, and the TYPEOF keyword handles the functionality.

In the SOQL query below, we will use the instanceOf keyword to determine whether an Account or Contact is related to a Task.

SObject record = [SELECT WhoId FROM Task WHERE Id = '00T5i00001itge9EAA'];
if (record instanceof Lead) {
    Account accountRecord = (Account) record;
    System.debug('Lead Name: ' + accountRecord.Name);
} else if (record instanceof Contact) {
    Contact contactRecord = (Contact) record;
    System.debug('Contact Name: ' + contactRecord.FirstName + ' ' + contactRecord.LastName);
}

After executing the above anonymous code, if the whole of the entered task is related to the Account, then it will return the Account name. If the word is related to Contact, the debug will return the First and Last name of the related contact record.

This way, we can determine the object type in the polymorphic SOQL using the instanceOf and TYPEOF keywords.

Comparison: Normal vs Polymorphic Relationship

FeatureNormal RelationshipPolymorphic Relationship
Object TypeFixedMultiple
FlexibilityLowHigh
Query ComplexityEasyMedium
Use CaseSimpleDynamic

Why Polymorphic Relationship is Important for Salesforce Developers

Polymorphic relationships are widely used in:

  • CRM systems
  • Activity tracking
  • Automation
  • Reporting

Understanding this concept helps you:

  • Write better SOQL queries
  • Reduce code complexity
  • Improve performance

Frequently Asked Questions

Q1: What is WhoId in Salesforce?

It refers to Contact or Lead

Q2: What is WhatId?

It refers to Account, Opportunity, and related entities.

Q3: Why use TYPEOF?

To fetch fields based on object type

Q4: Is a polymorphic relationship available in custom objects?

No

Conclusion

Polymorphic relationships in Salesforce SOQL provide a powerful way to handle dynamic relationships where a single field can refer to multiple object types. This makes Salesforce flexible and efficient for real-world applications.

By using features like TYPEOF, TYPE, and instanceOf, developers can write optimized queries and handle different object types in a single query. Understanding this concept is essential for every Salesforce developer who wants to build scalable and efficient applications.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.