MakeUseOf logo

GraphQL Queries and Mutations: What’s the Difference?

Woman writing "Use APIs" on a whiteboard
Image from Pexels. No attribution is needed
Mary writes for the programming section and has been doing so for the past two years. Her educational background is in Computer Science and Physics.
Sign in to your MakeUseOf account

GraphQL is a powerful query language that enables clients to request only the data they need from a server. It helps you increase request speeds since you can customize queries to only fetch specific data.

GraphQL has two operation types: queries and mutations. Despite their similarities, they serve quite different purposes.

Differences Between GraphQL Queries and Mutations

Queries and mutations are similar in that, you use them to make requests to GraphQL APIs. However, they differ in syntax, execution mode, and usage.

The Syntax of Queries and Mutations

The basic syntax of a GraphQL query is as follows:

query getProduct($id: ID!) {
 product(id: $id) {
 name
 price
 }
}

Here is what this code stands for:

  • query is the keyword that identifies the request as a query.
  • getProduct is the operation name
  • $id is the variable
  • ID! is the variable type.

If you don’t need the variables, omit them and define the query like this:

query getProducts {
 products {
 name
 price
 }
}

In some situations, you can omit the query keyword and name, writing a GraphQL query like this:

products {
 name
 price
}

While this format works, using the query keyword is better for readability.

The syntax of mutations is similar to queries except for using the mutation keyword.

mutation AddNewProduct ($name: String!, $price: Number!) { 
 addProduct(name: $name, price: $price) {
 name
 price
 }
}

Different Execution Modes

Another difference between a query and a mutation is that queries run in parallel while mutations run synchronously. When you run two mutations, they will execute one after another, in order

Contrasting Uses for Queries and Mutations

You should use queries for READ operations only. For example, use a query when fetching products from an API endpoint.

Use mutations for CREATE, UPDATE, and DELETE operations. These are essentially operations that alter the data stored in the database.

For example, use a mutation when updating a customer name via an orders endpoint.

Get Into the Habit of Using Queries and Mutations Appropriately

GraphQL is a powerful query language that enables you to request only the data you need. There are two operations you can perform in GraphQL: queries, and mutations.

These operations differ in syntax, execution, and their intended uses. You should use queries for READ operations and mutations for CREATE, UPDATE, and DELETE operations.

AltStyle によって変換されたページ (->オリジナル) /