Bird
Raised Fist0
GraphQLquery~20 mins

Union types in GraphQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Union Types Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the output of this GraphQL query using union types?

Given the schema with a union SearchResult = Photo | Person, and the query below, what is the expected output?

GraphQL
query {
  search(text: "john") {
    ... on Photo {
      id
      url
    }
    ... on Person {
      id
      name
    }
  }
}
A[{"id": "p1", "name": "John Doe"}, {"id": "u1", "url": "http://example.com/photo1.jpg"}]
B]}"gpj.1otohp/moc.elpmaxe//:ptth" :"lru" ,"1u" :"di"{ ,}"eoD nhoJ" :"eman" ,"1p" :"di"{[
C[{"id": "p1", "url": "http://example.com/photo1.jpg", "name": "John Doe"}]
DSyntaxError: Cannot query fields on union type without inline fragments
Attempts:
2 left
💡 Hint

Remember that when querying union types, you must use inline fragments to specify fields for each type.

🧠 Conceptual
intermediate
1:30remaining
Which statement about GraphQL union types is true?

Choose the correct statement about union types in GraphQL.

AUnion types can include scalar types like String or Int.
BUnion types are used to define fields that return lists of a single object type.
CUnion types require all member types to share the same fields.
DUnion types allow a field to return one of several object types but cannot include interfaces.
Attempts:
2 left
💡 Hint

Think about what types can be included in a union and how they differ from interfaces.

📝 Syntax
advanced
1:30remaining
Identify the syntax error in this GraphQL union type definition

Which option shows the correct syntax for defining a union type SearchResult that includes Photo and Person?

GraphQL
union SearchResult = Photo | Person
Aunion SearchResult = Photo | Person
Bunion SearchResult: Photo | Person
Cunion SearchResult { Photo | Person }
Dtype SearchResult = Photo | Person
Attempts:
2 left
💡 Hint

Recall the exact syntax for union type declarations in GraphQL SDL.

optimization
advanced
2:00remaining
How to optimize a query using union types to reduce data transfer?

You have a union type SearchResult = Photo | Person. You want to fetch only the id and name for Person and only the id and url for Photo. Which query is the most efficient?

Aquery { search(text: "abc") { ... on Person { id name url } ... on Photo { id url name } } }
Bquery { search(text: "abc") { id name url } }
Cquery { search(text: "abc") { ... on Person { id name } ... on Photo { id url } } }
Dquery { search(text: "abc") { id } }
Attempts:
2 left
💡 Hint

Think about how inline fragments help fetch only needed fields per type.

🔧 Debug
expert
2:30remaining
Why does this GraphQL query with union types fail?

Given the union type SearchResult = Photo | Person, why does this query fail?

query {
  search(text: "xyz") {
    id
    name
  }
}
ABecause the search field does not accept arguments.
BBecause fields must be queried inside inline fragments for union types.
CBecause the query is missing the __typename field.
DBecause the union type must be replaced with an interface in the query.
Attempts:
2 left
💡 Hint

Recall how to query fields on union types in GraphQL.

Practice

(1/5)
1. What is the main purpose of using union types in GraphQL?
easy
A. To group multiple object types into one field that can return different types
B. To define a list of scalar values
C. To create a new scalar type
D. To enforce a single object type for a field

Solution

  1. Step 1: Understand union type purpose

    Union types allow a field to return one of several object types, grouping them logically.
  2. Step 2: Compare with other options

    Defining a list of scalar values or creating a new scalar type describes scalars, not unions. Enforcing a single object type for a field contradicts the union concept.
  3. Final Answer:

    To group multiple object types into one field that can return different types -> Option A
  4. Quick Check:

    Union types = group multiple object types [OK]
Hint: Unions group different object types under one field [OK]
Common Mistakes:
  • Confusing union with scalar types
  • Thinking unions enforce a single type
  • Mixing unions with interfaces
2. Which of the following is the correct syntax to define a union type named SearchResult that includes User and Post types?
easy
A. type SearchResult = User & Post
B. union SearchResult = User | Post
C. interface SearchResult = User | Post
D. union SearchResult { User, Post }

Solution

  1. Step 1: Recall union syntax

    Unions use the syntax: union Name = Type1 | Type2 with pipe separators.
  2. Step 2: Check each option

    union SearchResult = User | Post matches correct syntax. type SearchResult = User & Post uses & which is for intersections, not unions. interface SearchResult = User | Post wrongly uses interface keyword. union SearchResult { User, Post } uses braces which is invalid for unions.
  3. Final Answer:

    union SearchResult = User | Post -> Option B
  4. Quick Check:

    Union syntax uses '=' and '|' [OK]
Hint: Use '=' and '|' to define unions, no braces [OK]
Common Mistakes:
  • Using '&' instead of '|'
  • Using braces {} instead of '='
  • Confusing union with interface syntax
3. Given the union type SearchResult = User | Post and this query:
{ search { ... on User { name } ... on Post { title } } }

What fields will be returned if the search result contains one User with name "Alice" and one Post with title "GraphQL Guide"?
medium
A. [{"name": "Alice"}]
B. [{"name": "Alice", "title": "GraphQL Guide"}]
C. [{"title": "GraphQL Guide"}]
D. [{"name": "Alice"}, {"title": "GraphQL Guide"}]

Solution

  1. Step 1: Understand inline fragments on union

    The query uses inline fragments to select name from User and title from Post.
  2. Step 2: Apply to data

    Since the result has one User and one Post, the response includes both objects separately with their respective fields.
  3. Final Answer:

    [{"name": "Alice"}, {"title": "GraphQL Guide"}] -> Option D
  4. Quick Check:

    Inline fragments return fields per type separately [OK]
Hint: Inline fragments return separate objects per type [OK]
Common Mistakes:
  • Combining fields into one object
  • Returning only one type's fields
  • Ignoring inline fragment usage
4. Consider this union definition:
union SearchResult = User | Post

And this query:
{ search { ... on User { id name } ... on Post { id title } } }

Which of the following errors will occur if you try to query a field email inside Post inline fragment like this:
{ search { ... on User { id name } ... on Post { id title email } } }
medium
A. Error: Field 'email' must be queried on User type
B. No error, query runs successfully
C. Error: Field 'email' does not exist on type 'Post'
D. Error: Union types cannot have inline fragments

Solution

  1. Step 1: Check Post type fields

    If email is not defined on Post type, querying it causes an error.
  2. Step 2: Understand inline fragment validation

    Inline fragments must only query fields existing on the specified type. Querying unknown fields causes errors.
  3. Final Answer:

    Error: Field 'email' does not exist on type 'Post' -> Option C
  4. Quick Check:

    Querying unknown fields on type causes error [OK]
Hint: Check if field exists on type before querying [OK]
Common Mistakes:
  • Assuming all fields exist on all union types
  • Thinking unions disallow inline fragments
  • Querying fields on wrong types
5. You have a union type SearchResult = User | Post | Comment. You want to write a query that returns the name for User, title for Post, and content for Comment. Which query correctly fetches these fields?
hard
A. { search { ... on User { name } ... on Post { title } ... on Comment { content } } }
B. { search { name title content } }
C. { search { ... on User { name } ... on Post { title } content } }
D. { search { ... on User { name } ... on Post { title } ... on Comment { title } } }

Solution

  1. Step 1: Use inline fragments for each union type

    Each type in the union requires its own inline fragment to query its specific fields.
  2. Step 2: Validate fields per type

    { search { ... on User { name } ... on Post { title } ... on Comment { content } } } queries name on User, title on Post, and content on Comment correctly. Other options either query fields directly without fragments or use wrong fields.
  3. Final Answer:

    { search { ... on User { name } ... on Post { title } ... on Comment { content } } } -> Option A
  4. Quick Check:

    Use inline fragments per type to query union fields [OK]
Hint: Use one inline fragment per union type with correct fields [OK]
Common Mistakes:
  • Querying all fields directly without fragments
  • Using wrong fields for a type
  • Mixing fields inside fragments incorrectly