Skip to the workspace
Pebellslearn by building
Mutations  ›  Lesson

Multiple Fields in a Mutation

Multiple Fields in Mutation 12 minThe top-level fields of a mutation run one after another in the order written, so later writes see earlier ones, but a failure in a later field does not undo an earlier one.

graphql / Multiple Fields in a Mutation

Explore each scene at your own pace.

01 · The rule

The rule

Multiple Fields in a Mutation

A shop admin runs a weekend sale: drop the price of The Quiet Ledger, then post a staff review to promote it. Both changes can go in one mutation request. But when one request does two writes, you need to know which happens first and what happens if the second fails.

The rule

Mutation fields run in order, each finishing before the next begins.

A mutation can list several top-level fields:

mutation WeekendSale {
  updatePrice(bookId: "b2", price: 299) {
    title
    price
  }
  addReview(input: { bookId: "b2", rating: 5, text: "Staff pick for the sale." }) {
    id
    book { price }
  }
}

GraphQL runs the top-level fields of a mutation serially: updatePrice runs completely, including its selected fields, and only then does addReview start. So the review's book { price } is guaranteed to show the new price, 299.

Queries are different. Their top-level fields have no side effects, so a server is free to resolve them in parallel. Only the top level of a mutation is serial; the fields nested inside each result resolve the normal way.

Two more rules follow from what you already know:

  • Same field twice needs aliases. Posting two reviews means two addReview fields with different arguments, so name them: first: addReview(...) and second: addReview(...).
  • Order is not a transaction. If addReview fails, the price change has already happened and stays. The response carries an error for the failed field. If two changes must succeed or fail together, give the schema one field, such as startSale, whose resolver does both inside a database transaction.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.