0
0
GraphqlComparisonBeginner · 3 min read

Query vs Mutation in GraphQL: Key Differences and Usage

Query in GraphQL is used to read or fetch data without changing it, while Mutation is used to create, update, or delete data. Queries are safe and idempotent, whereas mutations modify server-side data and may have side effects.
⚖️

Quick Comparison

This table summarizes the main differences between Query and Mutation in GraphQL.

FactorQueryMutation
PurposeFetch or read dataModify or write data
Side EffectsNo side effectsMay cause side effects
IdempotencyIdempotent (safe to repeat)Not necessarily idempotent
HTTP MethodUsually POSTUsually POST
ExecutionCan be parallelExecuted serially in order
ReturnReturns requested dataReturns modified data or status
⚖️

Key Differences

Query operations in GraphQL are designed to retrieve data from the server without causing any changes. They are safe to run multiple times and do not affect the server state. Because of this, queries can be cached and executed in parallel to improve performance.

On the other hand, Mutation operations are intended to change data on the server, such as creating, updating, or deleting records. Mutations may have side effects and are executed serially to maintain data consistency. They often return the updated data or confirmation of the change.

In summary, use Query when you want to get data without changing anything, and use Mutation when you want to change data on the server.

⚖️

Code Comparison

Here is an example of a Query to fetch a user's name and email by ID.

graphql
query GetUser {
  user(id: "123") {
    name
    email
  }
}
Output
{ "data": { "user": { "name": "Alice", "email": "alice@example.com" } } }
↔️

Mutation Equivalent

Here is an equivalent Mutation to update the user's email address.

graphql
mutation UpdateUserEmail {
  updateUser(id: "123", email: "newalice@example.com") {
    id
    name
    email
  }
}
Output
{ "data": { "updateUser": { "id": "123", "name": "Alice", "email": "newalice@example.com" } } }
🎯

When to Use Which

Choose Query when you need to read or fetch data without changing anything on the server. This keeps your operations safe and efficient.

Choose Mutation when you want to create, update, or delete data, as these operations modify the server state and may have side effects. Always use mutations for any data changes to keep your API clear and predictable.

Key Takeaways

Use Query to fetch data without changing server state.
Use Mutation to create, update, or delete data on the server.
Queries are safe and can run in parallel; mutations run serially to maintain consistency.
Mutations may have side effects; queries should not.
Choose the operation type based on whether you want to read or modify data.