function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Karthik jKarthik j 

How to write child to parent query for task object

Hi
I want write a soql query on the Task object to get a custom field on its parent. whatid is the relationship field between Taskand its parent. I wrote this query but it throwing error.

select id,what.Program_Name__c from Task

How I can achieve this.

Thanks in advance
CharuDuttCharuDutt
Hii Karthik
Try Below Query
SELECT Id, WhatId, Account.name FROM Task

SELECT whatid FROM task WHERE whatid in (select id from Account) GROUP BY whatid 
Please Mark It As Best Answer If It Helps
Thank You!
SwethaSwetha (Salesforce Developers) 
HI Karthik,

Your ask is similar to https://salesforce.stackexchange.com/questions/50995/how-do-i-access-custom-fields-of-task-parent-record-using-soql

WhatId is a polymorphic lookup field: it can refer to many different object types. Unless your org has the special SOQL Polymorphism feature turned on, you need to structure your relationship queries differently than standard SOQL dot notation.

Across the WhatId relationship, you can access at least the Type and Name fields with simple dot notation (SELECT What.Name, What.Type FROM Task WHERE ...)

However, if you want more data, you'll have to perform an entirely separate query that will vary by the type of the What entity.

If you are using Apex, you can break it into two separate queries.
Task t = [SELECT WhatId FROM Task WHERE Id = 'Task Id']; 
your_Object__c m = [SELECT id FROM My_Object__c WHERE Id =: t.WhatId];
Reference: https://salesforce.stackexchange.com/questions/220127/how-to-display-task-whatid-related-field-on-lightning-page

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you