I am using the polymorphism in my SOQL queries which is working fine, an generic example of the query is below
SELECT
TYPEOF What
WHEN Account THEN Phone, NumberOfEmployees
WHEN Opportunity THEN Amount, CloseDate
ELSE Name, Email
END
FROM Event
Now if i want to only query all the Event associated to all accounts which have a phone number of '123456', is that possible? I would need to use polymorphic fields in my where condition. I am trying the syntax but i am getting issues, not very sure if we can use polymorphism in where condition. What i am trying to get is something like this but is not working
SELECT TYPEOF What WHEN Account THEN Phone, NumberOfEmployees WHEN
Opportunity THEN Amount, CloseDate ELSE Name, Email END FROM Event
where TYPEOF What WHEN Account THEN Phone Else Name END ='123456'
Best Answer
Based on the current TYPEOF documentation that clause is only applicable within the SELECT statement.
You might need to use something like
What.Type = 'Account' and What.Phone = '123456'
in the SOQL query. Maybe build it up with some additional conditions.E.g.
Oddly, as @Anil observes in the comments, other Account fields produce an error:
gives:
I suspect the
What.Type = 'Account'
guard statement isn't preventing the column checking on the polymorphic What field.I was going to suggest that if all the types referenced by the field have the field being checked then the filter will work and if the field only belongs to a subset of the types they you will get the error. However, this doesn't appear to be the case either, as Campaign doesn't have a Phone field.