# Write a SOQL query using TYPEOF on Task to select Lead.Company if Who is a Lead, and Contact.Department if Who is a Contact.

**Topic:** Development · **Difficulty:** Hard · **Asked at:** Salesforce, Deloitte, PwC · **Tags:** soql, scenario, polymorphic, typeof

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-soql-query-using-typeof-on-task-to-select-lead-company-if-who-is-a-lead-and-contact-department-if-who

## Answer

`TYPEOF Who` returns different fields depending on whether the related record is a Lead or a Contact.

```soql
SELECT Id, Subject,
  TYPEOF Who
    WHEN Lead    THEN Company
    WHEN Contact THEN Department
  END
FROM Task
```
In Apex, check the type with `task.Who instanceof Lead` and cast to read the fields.

---
Source: ForceChallenges · last updated 2026-10-19
