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.
| Factor | Query | Mutation |
|---|---|---|
| Purpose | Fetch or read data | Modify or write data |
| Side Effects | No side effects | May cause side effects |
| Idempotency | Idempotent (safe to repeat) | Not necessarily idempotent |
| HTTP Method | Usually POST | Usually POST |
| Execution | Can be parallel | Executed serially in order |
| Return | Returns requested data | Returns 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.
query GetUser {
user(id: "123") {
name
email
}
}Mutation Equivalent
Here is an equivalent Mutation to update the user's email address.
mutation UpdateUserEmail {
updateUser(id: "123", email: "newalice@example.com") {
id
name
email
}
}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
Query to fetch data without changing server state.Mutation to create, update, or delete data on the server.