0
0
GraphqlHow-ToBeginner · 3 min read

How to Use Multiple Queries in One Request in GraphQL

In GraphQL, you can include multiple queries in one request by writing multiple named queries in the same request. Each query must have a unique name using operationName. This allows the server to distinguish and execute multiple queries in a single network call.
📐

Syntax

To run multiple queries in one request, you write each query with a unique operationName. This helps the server know which query to run or return results for.

Each query block looks like this:

  • query OperationName { ... } - defines a named query
  • Multiple such queries are placed one after another in the same request
graphql
query GetUser {
  user(id: "1") {
    id
    name
  }
}

query GetPosts {
  posts {
    id
    title
  }
}
💻

Example

This example shows a GraphQL request with two queries: one to get a user by ID and another to get a list of posts. Each query has a unique name.

graphql
query GetUser {
  user(id: "1") {
    id
    name
  }
}

query GetPosts {
  posts {
    id
    title
  }
}
Output
{ "data": { "user": { "id": "1", "name": "Alice" }, "posts": [ {"id": "101", "title": "GraphQL Basics"}, {"id": "102", "title": "Advanced GraphQL"} ] } }
⚠️

Common Pitfalls

One common mistake is not naming each query uniquely, which causes errors because GraphQL requires operation names when multiple queries are sent together.

Another issue is trying to send multiple unnamed queries without wrapping them properly, which is invalid syntax.

graphql
query {
  user(id: "1") {
    id
    name
  }
}

query {
  posts {
    id
    title
  }
}

# This will cause an error because both queries are unnamed.

# Correct way:
query GetUser {
  user(id: "1") {
    id
    name
  }
}

query GetPosts {
  posts {
    id
    title
  }
}
📊

Quick Reference

ConceptDescription
Multiple QueriesWrite multiple named queries separated by braces in one request.
Operation NameEach query must have a unique name when multiple queries are sent.
SyntaxUse query OperationName { ... } for each query.
ErrorUnnamed multiple queries cause syntax errors.

Key Takeaways

Use unique operation names for each query when sending multiple queries in one request.
Wrap each query in its own set of braces with the query OperationName syntax.
Sending multiple unnamed queries in one request causes errors.
Multiple queries in one request reduce network calls and improve efficiency.