# Fields, Aliases and Fragments — GraphQL

Source: https://www.skillbyai.com/en/graphql/q-fields

> Reusable selections.

## Select, rename and reuse

A query selects fields and nested fields; every leaf must be a scalar or enum. **Aliases** rename a field in the response so the same field can be requested twice with different arguments. **Fragments** name a reusable selection on a type and are spread with `...Name`; **inline fragments** (`... on Product`) select type-specific fields from interfaces and unions. In component-based UIs, each component often declares the fragment of data it needs.

## Shape the response

Aliases, fragments, variables and directives make queries reusable and precise.

![Three ideas: fields, aliases and fragments; variables and directives; introspection.](assets/figures/graphql/section-3-map.svg) — Figure 3.1 — Fragments, variables and introspection.

## Aliases and fragments

A GraphQL query.

```graphql
query ProductPage {
  featured: product(id: "7") { ...ProductCard }
  related: product(id: "9") { ...ProductCard }
  search(text: "lamp") {
    __typename
    ... on Product { name price { amount currency } }
    ... on User { name }
  }
}

fragment ProductCard on Product {
  id
  name
  price { amount currency }
}
```

## Request __typename for abstract types

Clients and caches need __typename to know which concrete type each union or interface result is.

**Quiz:** Why use an alias?

- [x] To request the same field more than once with different arguments
- [ ] To make a field optional
- [ ] To delete a field
- [ ] To change its type

*Answer:* To request the same field more than once with different arguments. Response keys must be unique.
