The difference between Mutation and Query

I'm reading GraphQL Docs about Query and Mutation. However, there is a lack of real examples which shows the difference and most importantly — when is it appropriate to use them.

Many thanks for the explanations.


Solution 1:

Short

Conventionally:

  • Query — for querying data (SELECT operations)
  • Mutation — for creating new and updating/deleting existing data (INSERT, UPDATE, DELETE)

Detailed

Technically any GraphQL query could be implemented to cause a data write. But there is a convention that any operations that cause writes should be sent explicitly via a mutation.

Besides the difference in the semantic, there is one important technical difference:

Query fields can be executed in parallel by the GraphQL engine while Mutation top-level fields MUST execute serially according to the spec:

If the operation is a mutation, the result of the operation is the result of executing the mutation’s top level selection set on the mutation root object type. This selection set should be executed serially.

It is expected that the top level fields in a mutation operation perform side‐effects on the underlying data system. Serial execution of the provided mutations ensures against race conditions during these side‐effects.

Source: https://graphql.github.io/graphql-spec/draft/#sec-Mutation

Solution 2:

In simple words the query is SELECT statement and mutation is INSERT Operation.

Query in graphql is used to fetch data while mutation is used for INSERT/UPDATE/DELETE operation.

Solution 3:

query = SELECT

mutation = INSERT, UPDATE, DELETE

Solution 4:

Query:

It should be used only for READ operations on the database.

Mutation:

It should be used only when you perform CREATE / UPDATE / DELETE something in the database.

Summary

If you just intend to read data without modifying(means without deleting, editing or creating) anything in your database, use a query. If you intend to delete, create, anything at database level, use a mutation.

This is what the documentation says here:

In REST, any request might end up causing some side-effects on the server, but by convention it's suggested that one doesn't use GET requests to modify data. GraphQL is similar - technically any query could be implemented to cause a data write. However, it's useful to establish a convention that any operations that cause writes should be sent explicitly via a mutation.

Just like in queries, if the mutation field returns an object type, you can ask for nested fields. This can be useful for fetching the new state of an object after an update.

There's one important distinction between queries and mutations, other than the name:

While query fields are executed in parallel, mutation fields run in series, one after the other.This means that if we send two incrementCredits mutations in one request, the first is guaranteed to finish before the second begins, ensuring that we don't end up with a race condition with ourselves.