I am using an soql query to get tasks. My requirement is to get all tasks which are related account or contact object. Also few other fields inside Account or contact object whichever the object related. Is there a simple way instead of writing multiple queries.
3 Answers
Please provide more specific information next time. Generally speaking you can refer to a parent object by reference name followed with a dot. Here is an example
Select Account.Name, AccountId From Task Where Account.Name = 'John'
Here Account is the name of the reference (from task) and AccountId is the referencing field.

- 3,738
- 2
- 26
- 35
-
[Select t.subject,t.Description,t.Id, t.WhatId From Task t ] is my query but I require only those tasks related to Account or contact other way what field should contain Account or contact id – Shebin Mathew Nov 06 '13 at 11:18
-
So it should be Where AccountId != null Or WhatId != null – Moti Korets Nov 06 '13 at 12:27
Your question is a little unclear. Are you looking for all TASKS related to any ACCOUNT or CONTACT or related to specific ACCOUNTS or CONTACTS?
If the former, try
SELECT Id, Subject, FROM TASK WHERE What.Type = 'Account' OR Who.Type = 'Contact'
if the latter, use the IN :list
syntax already suggested by Moti. The What.Type
is useful, as opposed to AccountId!=null
, because it will not return TASKS associated with, for example, OPPORTUNITIES (if you want that behavior, use AccountId!=null
and maybe drop the Who.Type
if you associate all CONTACTS with OPPORTUNITIES, as it would be redundant).
In either case, your issue will be pulling specific data from CONTACT whos, as polymorphic fields only allow access to a limited number of fields. Can't seem to find that list right now. I don't believe old SOQL supports the kind of the syntax to do that in one query--that's why SOQL polymorphism made such a bang--though I could be wrong.
Now, if you have SOQL TYPEOF available to you, you should be able to do something more interesting like:
SELECT Id, Subject, TYPEOF What WHEN Account THEN AccountNumber END, TYPEOF Who WHEN Contact THEN FirstName END FROM Task WHERE What.Type = 'Account' OR Who.Type = 'Contact'

- 1,183
- 10
- 17
How about
select {column list] from task where parentid in (select id from account where ...) or parentid in (select id from contact where ...)
Alternatively, if you're inside Apex and already have the contact or account ids in a list (we'll use idList), you can use:
select {column list] from task where parentid in :idList

- 2,864
- 1
- 21
- 15
-
Sorry I cannot use the account or contact ids to filter the query. I just want all tasks where what field contains Account or Contact ids. Smply tasks related to Account or Contact object – Shebin Mathew Nov 06 '13 at 11:20