# Multiple-Query Execution

GraphQL by PoP can execute multiple queries in a single operation.

Executing queries independently, and then all together as a single operation

This functionality is currently not part of the GraphQL spec, but it has been requested:

This feature improves performance, for whenever we need to execute an operation against the GraphQL server, then wait for its response, and then use that result to perform another operation. By combining them together, we are saving this extra request.

This is not query batching. When doing query batching, the GraphQL server executes multiple queries in a single request. But those queries are still independent from each other. They just happen to be executed one after the other, to avoid the latency from multiple requests.

In this case, all queries are combined together, and executed as a single operation. That means that they will reuse their state and their data. For instance, if a first query fetches some data, and a second query also accesses the same data, this data is retrieved only once, not twice.

When running this query (selecting query with name "__ALL"), the same data for entities of type Post and User is referenced by the 2 queries, and this data is retrieved from the database only once.

query GetUserData {
  users {
    name
    posts {
      title
      url
    }
  }
}

query GetPostData {
  posts {
    title
    url
    author {
      name
    }
  }
}

TIP

GraphiQL currently does not allow to execute multiple queries as a single operation.

To overcome this problem, if the operation name is __ALL, then the GraphQL server will execute all the submitted queries.

Then, attach the following query to the GraphiQL editor:

query __ALL { id }

And select this one when clicking on the "Run" button.

The @export directive additionally enables to have the results of a query injected as an input into another query. Running this query to see how the user's name obtained in the first query is used to search for posts in the second query.

# Export the user's name
query GetUserName {
  user(id:1) {
    name @export(as: "_search")
  }
}

# Search for posts with the user's name from the previous query
query SearchPosts($_search: String = "") {
  posts(searchfor: $_search) {
    title
  }
}
Last Updated: 8/11/2020, 12:57:43 PM