# Write a SOQL query to fetch all child Accounts, parent Accounts, and grandparent Accounts up to 4 levels up (Parent.Parent.Parent.Name).

**Topic:** Development · **Difficulty:** Medium · **Asked at:** TCS, Wipro, Tech Mahindra · **Tags:** soql, scenario, hierarchy, child-to-parent

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-soql-query-to-fetch-all-child-accounts-parent-accounts-and-grandparent-accounts-up-to-4-levels-up

## Answer

Walk up the hierarchy through the self-lookup `ParentId` using chained `Parent` relationships (up to 5 levels allowed in one path).

```soql
SELECT Id, Name, Parent.Name, Parent.Parent.Name, Parent.Parent.Parent.Name, Parent.Parent.Parent.Parent.Name
FROM Account
```
Each row shows the Account and its parent, grandparent and ancestors up to four levels up. Missing levels return null.

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