Queries, Variables and Fragments
Harry
· 14 Sep 2026
· 1 views
Advertisement
Arguments
Fields can take arguments to filter or shape results:
query {
posts(first: 5, category: "tech") {
title
}
}
Variables
Hard-coding values into a query string is fragile. Declare variables and pass them separately – the query becomes reusable and safe from injection:
query GetUser($id: ID!) {
user(id: $id) {
name
email
}
}
// variables sent alongside the query
{ "id": "1" }
Fragments
A fragment is a named, reusable set of fields – handy when several queries need the same shape:
fragment PostFields on Post {
id
title
createdAt
}
query {
featured { ...PostFields }
recent { ...PostFields }
}
Aliases
Ask for the same field twice with different arguments by aliasing them:
query {
today: posts(date: "2026-09-15") { title }
yesterday: posts(date: "2026-09-14") { title }
}
Subscriptions (real-time)
Alongside Query and Mutation, GraphQL has Subscription for live data pushed over a WebSocket – e.g. a chat message stream. Clients subscribe and receive updates as they happen.
Key points
- Fields take arguments to filter and shape results.
- Use variables (
$id) to make queries reusable and safe. - Fragments reuse a set of fields across queries.
- Aliases fetch the same field multiple ways; subscriptions deliver real-time data.