Aliases and Fragments
You'll learn how to rename query results and reuse common field selections in GraphQL.
What are Aliases?
When you query the same type multiple times with different arguments, GraphQL needs a way to distinguish the results. Aliases let you rename fields in the response so they don't collide.
Without aliases, you can't fetch two users in one query because both would try to use the key user. With aliases, you can:
{
admin: user(id: "1") {
name
email
}
guest: user(id: "2") {
name
email
}
}
The response uses your custom names:
{
"admin": { "name": "Alice", "email": "alice@example.com" },
"guest": { "name": "Bob", "email": "bob@example.com" }
}
Think of aliases like variable assignment—you're storing the result under a name you choose.
What are Fragments?
Notice how both queries above repeat name and email? Fragments are reusable units that define a set of fields on a type. They eliminate repetition:
fragment UserDetails on User {
name
email
}
{
admin: user(id: "1") {
...UserDetails
}
guest: user(id: "2") {
...UserDetails
}
}
The ... syntax "spreads" the fragment's fields into that location. If you later add phone to UserDetails, both queries automatically include it.
Fragments work like functions or templates—define once, use everywhere.
When to Use Them
Use aliases when querying the same field with different arguments. Use fragments when the same field selection appears multiple times across your queries.
Key Takeaway: Aliases rename fields to avoid conflicts, while fragments create reusable field selections—both keep your GraphQL queries clean and maintainable.