0
0
GraphQLquery~5 mins

Field selection in GraphQL

Choose your learning style9 modes available
Introduction

Field selection lets you choose exactly which pieces of data you want from a database. This helps you get only what you need, making your data faster and easier to use.

When you want to get just the name and email of users, not all their details.
When you need only the title and author of books in a library database.
When you want to load a list of products with only their price and name for a quick display.
When you want to reduce data transfer by asking for fewer fields in a query.
When you want to avoid showing sensitive information like passwords or private data.
Syntax
GraphQL
query {
  entityName {
    field1
    field2
    ...
  }
}

Replace entityName with the name of the data you want.

List only the fields you want inside the curly braces.

Examples
This gets the name and email fields of the user entity.
GraphQL
query {
  user {
    name
    email
  }
}
This fetches the title and author fields from book.
GraphQL
query {
  book {
    title
    author
  }
}
This gets the id and price of each product.
GraphQL
query {
  product {
    id
    price
  }
}
Sample Program

This query asks for the id and name fields of all users.

GraphQL
query {
  user {
    id
    name
  }
}
OutputSuccess
Important Notes

You can select as many or as few fields as you want.

If you don't select any fields, the query will be invalid.

Field selection helps reduce the amount of data sent over the network.

Summary

Field selection lets you pick exactly what data you want.

This makes your queries faster and your apps lighter.

Always select only the fields you need.