Nested Queries and Relationships
What you'll learn: How to fetch related data in a single GraphQL request by traversing object relationships.
One of GraphQL's superpowers is its ability to retrieve interconnected data in a single round-trip. Unlike REST APIs where you might need multiple requests to fetch related resources (like a user, then their posts, then comments on those posts), GraphQL lets you express these relationships directly in your query structure.
How Nested Queries Work
When your GraphQL schema defines relationships between types, you can "nest" your queries to follow those connections. If a User type has a posts field that returns an array of Post objects, you simply include posts in your query and specify which fields of each post you want.
Think of it like drilling down through a family tree: you start with a person, then request their children, then their children's spouses, all in one question.
Query Structure
query {
user(id: "123") {
name
email
posts {
title
publishedAt
comments {
text
author {
name
}
}
}
}
}
This single query traverses three levels of relationships: from user to posts to comments to comment authors. The server resolves each level using the resolvers defined in your schema, and returns a nested JSON object matching your query shape.
Why This Matters
Nested queries eliminate the "N+1 problem" common in REST, where fetching related data requires multiple sequential requests. You get exactly the data you need, shaped the way you need it, in one go.
Key Takeaway: GraphQL nested queries let you traverse object relationships and fetch deeply connected data in a single request, following the exact structure you define in your query.