Polymorphic Field in SOQL Queries in Salesforce

Polymorphic Field in SOQL Queries in Salesforce

instanceof can be used to find the object type in Salesforce Apex.

TYPEOF can be used to find the object type in Salesforce SOQL.

For Task Object with What field:

Apex:

List < Task > listTasks =
[ SELECT Id, Subject,  
    TYPEOF What
    WHEN Opportunity THEN Name, Amount
    END
FROM Task
LIMIT 15 ];

for ( Task objTask : listTasks ) {

    System.debug( objTask.Subject );

    if ( objTask.What instanceof Opportunity ) {
    
        Opportunity objOpportunity = objTask.What;
        System.debug( objOpportunity.Name );
        System.debug( objOpportunity.Amount );
       
    }
    
}

SOQL:

SELECT WhatId 
FROM Task 
WHERE What.Type = 'Opportunity'

For Conversation Entry Object with Conversation field:

Apex:

List < ConversationEntry > listCEs =
[ SELECT Id, ActorName, ActorType, EntryType, Message,  
    TYPEOF Conversation
    WHEN MessagingSession THEN MessagingChannel.DeveloperName, PreviewDetails
    ELSE Name
    END
FROM ConversationEntry
LIMIT 15 ];

for ( ConversationEntry objCE : listCEs ) {

    if ( objCE.Conversation instanceof MessagingSession ) {
    
        MessagingSession objMS = objCE.Conversation;
        System.debug( objMS.MessagingChannel.DeveloperName );
        System.debug( objMS.PreviewDetails );
       
    }
    
}

SOQL:

SELECT MessagingChannel.DeveloperName, PreviewDetails
FROM MessagingSession
WHERE Id IN (
    SELECT ConversationId 
    FROM ConversationEntry 
    WHERE CreatedDate = LAST_N_DAYS:15
)

Leave a Reply