SOQL for Polymorphic relationships

You can leverage TYPEOF keyword in your SOQL queries!

Do you use polymorphic relationships?

You can leverage TYPEOF keyword in your SOQL queries!

sql
SELECT
    Id,
    WhoId,
    TYPEOF Who
        WHEN Contact THEN Name, Account.Name
        WHEN Lead THEN Id, Company
    END
FROM Task

Now instead:

Don't do this
for(Lead lead: [SELECT Id, OwnerId, Owner.Name, Owner.Type, Owner.Email, Owner.Phone FROM Lead]) {
    if(lead.OwnerId.startsWith('005')){
        ...
    } else {
        ...
    }
}

Do the following:

Do this
for(Lead lead: [
    SELECT
        Id,
        OwnerId,
        TYPEOF Owner WHEN Group THEN Name, Type WHEN User THEN Name, Email, Phone END
    FROM Lead
]) {
    if(lead.Owner instanceof Group) {
        ...
    } else {
        ...
    }
}

Text and code were extracted from the original slide. Plain-text version of the whole catalog