Thuta Learning
GraphQL
IntermediateWeb Developmentbeginner

Unions and Fragments

What you'll walk away with

  • Explain the core ideas behind Unions and Fragments
  • Run the sample GraphQL query or code and verify its output
  • Apply the technique correctly to the Tutorial Platform and production scenarios

Build the mental model

A `union` is similar to an interface but its member types do not need any shared fields — it fits queries that can return unrelated object shapes, like a search result. Querying a union requires inline fragments such as `... on Tutorial` to request type-specific fields. A named fragment (`fragment TutorialCard on Tutorial { ... }`) lets you reuse the same field selection across multiple queries.

Connect it to a real scenario

Model the site-wide search feature with `union SearchResult = Tutorial | Author`. Write a `TutorialCard` fragment once for the card component's field list and reuse it in both the homepage query and the search query — changing the field list means editing just one place.

Try the working example

graphql
union SearchResult = Tutorial | Author

fragment TutorialCard on Tutorial {
  id
  title
  difficulty
}

query Search($term: String!) {
  search(term: $term) {
    ... on Tutorial {
      ...TutorialCard
    }
    ... on Author {
      id
      name
    }
  }
}
You should see
You can query a union type and reuse a field selection with a fragment.

5-minute try-it

Write a `union NotificationTarget = Tutorial | Comment` and a query that uses two inline fragments to select from it.

One important caution

Selecting scalar fields directly on a union without inline fragments causes a validation error, because union members have no guaranteed shared fields.

GraphQL — Queries and Mutations (Fragments)GraphQL

Easy traps

  • Selecting scalar fields directly on a union without inline fragments causes a validation error, because union members have no guaranteed shared fields.
  • Validate sample queries and mutations on a local or test server with recoverable data before applying them to production.

Exercise

Write a `union NotificationTarget = Tutorial | Comment` and a query that uses two inline fragments to select from it.

You'll know it worked when: You can query a union type and reuse a field selection with a fragment.

Unions and Fragments | Thuta Learning