0
0
GraphQLquery~5 mins

Over-fetching and under-fetching problems in GraphQL

Choose your learning style9 modes available
Introduction

Over-fetching and under-fetching happen when you get too much or too little data from a database. This can slow down apps or make them miss needed info.

When a mobile app loads a user profile but gets extra unused details, slowing it down.
When a website asks for only a user's name but the server sends the whole user record.
When a dashboard needs sales totals but the query returns every sale detail, making it slow.
When an app requests a list of products but only gets one product's info, missing others.
When a report needs customer emails but the query misses that field, causing errors.
Syntax
GraphQL
query {
  entityName {
    field1
    field2
    ...
  }
}

GraphQL queries specify exactly which fields you want.

This helps avoid over-fetching by not asking for extra fields.

Examples
This query fetches only the user's id and name, avoiding extra data.
GraphQL
query {
  user {
    id
    name
  }
}
Fetches only the title and content of posts, no extra fields.
GraphQL
query {
  posts {
    title
    content
  }
}
Fetches specific product details by id, avoiding unrelated data.
GraphQL
query {
  product(id: "123") {
    name
    price
  }
}
Sample Program

This query asks for only the id, name, and email of user with id 1, avoiding extra fields like address or phone.

GraphQL
query {
  user(id: "1") {
    id
    name
    email
  }
}
OutputSuccess
Important Notes

Over-fetching wastes bandwidth and slows apps.

Under-fetching means you may need extra queries, causing delays.

GraphQL helps fix these by letting you ask for exactly what you need.

Summary

Over-fetching means getting more data than needed.

Under-fetching means getting less data than needed.

GraphQL queries solve these by letting you specify exact fields.