Queries, Arguments, Variables, and Nesting
🎯 Introduction
Now that you understand schemas, let's return to the client. Queries involve more than selecting fields: real applications need to filter data, reuse query documents, and retrieve several levels of related data at once.
This article covers four everyday query techniques: passing arguments to fields, supplying dynamic values through variables, querying a field multiple times with aliases, and fetching related data through nested queries. Together, these cover most common query needs.
🧱 Field Arguments
Query fields can accept arguments much like functions. To fetch a single user by ID, first declare the argument in the schema's Query type:
type Query {
users: [User!]!
user(id: ID!): User
}
user(id: ID!) requires an id argument of type ID. The client writes:
{
user(id: "1") {
username
age
}
}
On the server, arguments are available through the resolver's second parameter, args:
const resolvers = {
Query: {
user: (parent, args) => users.find((item) => item.id === args.id),
},
};
Resolvers have a defined parameter order. The first two are used most often:
parent: the value resolved at the previous level. It is usually unused in root queries but essential for nested fields, as we will see shortly.args: an object containing the arguments supplied by the client.
!). Missing required arguments or incorrect types fail validation before execution, so resolvers do not need to check them manually.✨ Query Variables
The previous example hard-codes "1" in the query. In real applications, the ID is dynamic, often coming from a user interaction. Rather than constructing query strings each time, use GraphQL variables:
query GetUser($id: ID!) {
user(id: $id) {
username
age
}
}
Here is the new syntax:
query GetUser: names the operationGetUser, which helps with debugging and investigating logs.($id: ID!): declares a required variable$idof typeID. Variable names start with$.user(id: $id): uses the variable in the query.
Variable values are sent alongside the query as a separate JSON object, rather than embedded in the query text. In Apollo Sandbox's Variables panel at the bottom left, enter:
{
"id": "1"
}
This has two clear benefits: the query document stays reusable while values change, and it avoids escaping problems caused by string concatenation. The idea is similar to parameterized SQL queries that keep values separate from query text.
⚡ Aliases: Querying a Field Multiple Times
To compare two users in one request, writing user twice with different arguments would cause a field conflict. Use aliases:
{
first: user(id: "1") {
username
}
second: user(id: "2") {
username
}
}
An alias uses the syntax alias: originalField. The response uses the alias as its key:
{
"data": {
"first": { "username": "Alex" },
"second": { "username": "Emma" }
}
}
Aliases are not limited to fields with arguments. They are a useful way to resolve response-name conflicts wherever they arise in a query.
🛠 Nested Queries and Resolver Chains
Fetching related data in a single query is one of GraphQL's strengths compared with REST. We defined the relationship between User and Article in the previous article; now let's implement it.
Start with mock data. Each article records its author using authorId:
export const users = [
{ id: '1', username: 'Alex', age: 20 },
{ id: '2', username: 'Emma', age: 22 },
];
export const articles = [
{ id: '1', title: 'Getting Started with GraphQL', authorId: '1' },
{ id: '2', title: 'Vue 3 in Practice', authorId: '1' },
{ id: '3', title: 'Node.js Basics', authorId: '2' },
];
Add an articles field to User in the schema:
type Article {
id: ID!
title: String!
}
type User {
id: ID!
username: String!
articles: [Article!]!
}
The key is in the resolvers. User objects in the users array do not have an articles property, so define a resolver on User to tell GraphQL how to fetch each user's articles:
const resolvers = {
Query: {
users: () => users,
user: (parent, args) => users.find((item) => item.id === args.id),
},
User: {
articles: (parent) =>
articles.filter((item) => item.authorId === parent.id),
},
};
This is where parent comes in. When the client requests a user's articles, parent is the user object resolved at the previous level. Use parent.id to filter the article array.
Think of it as a relay: Query.users retrieves the user list, then User.articles receives each user as parent and retrieves that user's articles. The client only needs one query:
{
users {
username
articles {
title
}
}
}
The result contains each user and their article list. With REST, this commonly requires fetching the user list and then requesting articles separately for each user.
User.articles. For fields such as username, GraphQL's default resolver reads the matching property from the object, so you do not need to write one.❓ Questions and Answers
Q1: Is the operation name GetUser required?
No, but naming operations is a useful habit. Operation names can be recorded in server logs, making it easier to identify a failing query in production.
Q2: Can variables contain objects or arrays?
Yes. Variables support schema-defined input types, including the input object types covered later. These are useful for passing complex mutation data.
Q3: Can nested queries cause performance problems?
Yes. If fetching articles runs a database query for each user, 100 users mean 100 additional queries. This is the N+1 problem. For now, understand the concept; in real applications, DataLoader can batch these requests.
Q4: Can a field accept multiple arguments?
Yes. Separate them with commas, as in articles(first: Int, after: String). Resolvers access them through args.first and args.after, a common pattern for pagination.
Q5: What is parent in a root Query resolver?
A root query has no previous level. Its parent is a root value that is rarely needed. Unused parameters can be omitted where possible, or represented with a placeholder such as _.
🧪 Exercises
Exercise 1: Add article(id: ID!): Article to Query and write a query using a variable. Pass "1" and "99" in Sandbox and observe the result when no article is found.
# Write your code here
Exercise 2: Following User.articles, add author: User! to Article and implement its resolver. Retrieve every article's title and author name in one query.
const resolvers = {
Article: {
// Write your code here
},
};
🎉 You now know the common GraphQL query techniques! Our data is still read-only. Next, we will use mutations to create, update, and delete data.
