How to Write Named Query in GraphQL: Syntax and Examples
In GraphQL, a named query is written by starting the query with the
query keyword followed by a name, like query GetUser. This name helps identify the query in tools and logs, and the syntax looks like query QueryName { ... }.Syntax
A named query in GraphQL starts with the query keyword, followed by a unique name for the query. Inside curly braces { }, you specify the fields you want to fetch. Naming your query helps with debugging and caching.
- query: keyword to start a query operation
- QueryName: a unique name you choose for the query
- { ... }: the selection set of fields to fetch
graphql
query GetUser {
user(id: "1") {
id
name
email
}
}Example
This example shows a named query called GetUser that fetches a user's id, name, and email by their id. The name helps identify this query in tools like GraphiQL or Apollo Client.
graphql
query GetUser {
user(id: "1") {
id
name
email
}
}Output
{
"data": {
"user": {
"id": "1",
"name": "Alice",
"email": "alice@example.com"
}
}
}
Common Pitfalls
Common mistakes when writing named queries include:
- Omitting the query name, which makes it an anonymous query and harder to debug.
- Using invalid characters or spaces in the query name.
- Confusing the query name with the operation type or field names.
Always start with query keyword followed by a valid name without spaces.
graphql
/* Wrong: Anonymous query without a name */ { user(id: "1") { id name } } /* Right: Named query with valid name */ query GetUser { user(id: "1") { id name } }
Quick Reference
| Part | Description | Example |
|---|---|---|
| query | Keyword to start a query operation | query |
| QueryName | Unique name for the query, no spaces | GetUser |
| Selection Set | Fields to fetch inside braces | { user { id name } } |
Key Takeaways
Always start a named query with the 'query' keyword followed by a unique name.
Use named queries to improve debugging and caching in GraphQL tools.
Avoid spaces or special characters in query names to prevent syntax errors.
Anonymous queries work but are less helpful for identifying operations.
The selection set inside braces defines what data the query returns.