0
0
GraphqlComparisonBeginner · 3 min read

GraphQL Query vs Mutation vs Subscription: Key Differences and Usage

In GraphQL, a 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.

AspectQueryMutationSubscription
PurposeFetch dataModify dataReal-time data updates
Operation TypeRead-onlyWrite (create/update/delete)Continuous stream
ConnectionSingle request-responseSingle request-responsePersistent connection
Side EffectsNoYesYes
Typical Use CaseGet user infoUpdate user profileLive chat messages
ResponseReturns requested dataReturns modified dataPushes 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

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

Mutation Equivalent

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

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

Use Query for safe, read-only data fetching.
Use Mutation to change data with side effects.
Use Subscription for real-time, continuous data updates.
Queries and mutations are single operations; subscriptions keep a live connection.
Choose the operation type based on whether you need data reading, writing, or live updates.