GraphQL Query vs Mutation vs Subscription: Key Differences and Usage
Query is used to fetch data, a Mutation is used to modify data, and a Subscription enables real-time updates by listening to data changes. Queries and mutations are one-time operations, while subscriptions keep a live connection open for continuous data flow.Quick Comparison
This table summarizes the main differences between Query, Mutation, and Subscription in GraphQL.
| Aspect | Query | Mutation | Subscription |
|---|---|---|---|
| Purpose | Fetch data | Modify data | Real-time data updates |
| Operation Type | Read-only | Write (create/update/delete) | Continuous stream |
| Connection | Single request-response | Single request-response | Persistent connection |
| Side Effects | No | Yes | Yes |
| Typical Use Case | Get user info | Update user profile | Live chat messages |
| Response | Returns requested data | Returns modified data | Pushes data on events |
Key Differences
Query operations in GraphQL are designed to retrieve data without changing anything on the server. They are safe and idempotent, meaning you can run them multiple times without side effects.
Mutation operations are used to create, update, or delete data. They can cause side effects and change the server state. Mutations run sequentially to ensure data consistency.
Subscription operations establish a persistent connection (usually via WebSocket) to the server. They allow clients to receive real-time updates whenever specific data changes, making them ideal for live features like notifications or chat.
Query Code Example
query GetUser {
user(id: "1") {
id
name
email
}
}Mutation Equivalent
mutation UpdateUserEmail {
updateUser(id: "1", email: "alice.new@example.com") {
id
name
email
}
}When to Use Which
Choose Query when you need to read or fetch data without changing anything. Use Mutation when you want to create, update, or delete data on the server. Opt for Subscription when your app requires real-time updates, such as live notifications, chat messages, or streaming data.
Key Takeaways
Query for safe, read-only data fetching.Mutation to change data with side effects.Subscription for real-time, continuous data updates.