📖 Scenario: You are building a simple GraphQL API for a bookstore. The bookstore wants to allow users to query the list of books and sort them by different fields such as title or price.
🎯 Goal: Create a GraphQL query that accepts a sortBy argument to sort the list of books by the specified field.
📋 What You'll Learn
Define a GraphQL type Book with fields id, title, and price.
Create a query books that accepts a sortBy argument of type String.
Implement sorting logic in the resolver to return books sorted by the sortBy argument.
Support sorting by title and price only.
💡 Why This Matters
🌍 Real World
Sorting query results is a common feature in APIs to help users find data in the order they want, such as sorting products by price or name.
💼 Career
Understanding how to add arguments and sorting logic in GraphQL queries is essential for backend developers building flexible and user-friendly APIs.
Progress0 / 4 steps
1
Define the Book type and sample data
Create a GraphQL type called Book with fields id (ID!), title (String!), and price (Float!). Also, create a sample list of books called booksData with exactly these entries: { id: "1", title: "The Hobbit", price: 10.99 }, { id: "2", title: "1984", price: 8.99 }, and { id: "3", title: "Brave New World", price: 9.99 }.
GraphQL
Hint
Use type Book { ... } to define the type and create a constant array booksData with the given objects.
2
Add the sortBy argument to the books query
Add a query called books that returns a list of Book items. Add a sortBy argument of type String to this query.
GraphQL
Hint
Define a Query type with a books field that takes sortBy: String and returns a list of Book.
3
Implement resolver with sorting logic
Write a resolver function for books that accepts the sortBy argument. Sort the booksData array by title if sortBy is "title", or by price if sortBy is "price". Return the sorted array. If sortBy is not provided or invalid, return the original array unsorted.
GraphQL
Hint
Use args.sortBy to check the sorting field and return a new sorted array using Array.sort(). Use localeCompare for string sorting.
4
Complete the schema and export
Add the final code to create the executable schema using makeExecutableSchema from @graphql-tools/schema with the defined typeDefs and resolvers. Export the schema as schema.
GraphQL
Hint
Use makeExecutableSchema with typeDefs and resolvers and export the result as schema.
Practice
(1/5)
1. What does the orderBy argument do in a GraphQL query?
easy
A. It sorts the returned data by a specified field and direction.
B. It filters the data to only include certain fields.
C. It limits the number of results returned.
D. It groups the data by a specific field.
Solution
Step 1: Understand the purpose of orderBy
The orderBy argument is used to arrange data in a specific order based on a field.
Step 2: Identify sorting behavior
It sorts data either ascending (ASC) or descending (DESC) by the chosen field.
Final Answer:
It sorts the returned data by a specified field and direction. -> Option A
Quick Check:
Sorting = orderBy usage [OK]
Hint: Remember: orderBy controls sorting order in queries [OK]
Common Mistakes:
Confusing orderBy with filtering or limiting results
Thinking orderBy groups data instead of sorting
Assuming orderBy changes the data fields returned
2. Which of the following is the correct syntax to sort users by their name in ascending order using orderBy?
easy
A. { users(orderBy: [name, ASC]) { id name } }
B. { users(orderBy: name ASC) { id name } }
C. { users(orderBy: { name: ASC }) { id name } }
D. { users(orderBy: { ASC: name }) { id name } }
Solution
Step 1: Review GraphQL orderBy syntax
The correct syntax uses an object with the field as key and direction as value inside curly braces.
Step 2: Match syntax to options
{ users(orderBy: { name: ASC }) { id name } } matches this pattern: { name: ASC }. Others use incorrect formats.
Final Answer:
{ users(orderBy: { name: ASC }) { id name } } -> Option C
Quick Check:
Correct orderBy syntax = { users(orderBy: { name: ASC }) { id name } } [OK]
Hint: Use curly braces with field: direction inside orderBy [OK]
Common Mistakes:
Using parentheses or brackets incorrectly in orderBy
Placing direction before field name
Omitting curly braces around orderBy argument
3. Given this GraphQL query:
{ products(orderBy: { price: DESC }) { id name price } }
What will be the order of products in the result?
medium
A. Products sorted by price from highest to lowest.
B. Products sorted by price from lowest to highest.
C. Products sorted alphabetically by name.
D. Products returned in random order.
Solution
Step 1: Identify sorting field and direction
The query uses orderBy: { price: DESC }, meaning sort by price descending.
Step 2: Understand descending order
Descending order means highest values come first, then lower values.
Final Answer:
Products sorted by price from highest to lowest. -> Option A
Quick Check:
DESC means highest to lowest [OK]
Hint: DESC means descending (high to low), ASC means ascending (low to high) [OK]
Common Mistakes:
Confusing DESC with ascending order
Assuming sorting is by name instead of price
Thinking orderBy does not affect order
4. You wrote this query to sort posts by date ascending:
{ posts(orderBy: { date: ASC }) { id title date } }
But you get an error. What is the likely mistake?
medium
A. You must use sortBy instead of orderBy.
B. The orderBy argument should be a list, not an object.
C. The direction ASC is not valid in GraphQL.
D. The date field is missing from the schema.
Solution
Step 1: Check schema fields
If date is not defined in the posts schema, sorting by it causes an error.
Step 2: Validate other options
orderBy accepts an object, ASC is valid, and sortBy is not standard GraphQL.
Final Answer:
The date field is missing from the schema. -> Option D
Quick Check:
Sorting field must exist in schema [OK]
Hint: Ensure sorting field exists in schema before using orderBy [OK]
Common Mistakes:
Using invalid direction keywords
Confusing orderBy with other arguments
Assuming orderBy requires a list always
5. You want to fetch a list of employees sorted first by department ascending, then by salary descending. Which orderBy argument correctly achieves this?
hard
A. { employees(orderBy: { department: ASC, salary: DESC }) { id name department salary } }
B. { employees(orderBy: [{ department: ASC }, { salary: DESC }]) { id name department salary } }
C. { employees(orderBy: [department: ASC, salary: DESC]) { id name department salary } }
D. { employees(orderBy: { salary: DESC, department: ASC }) { id name department salary } }
Solution
Step 1: Understand multi-level sorting syntax
To sort by multiple fields, orderBy usually takes a list of objects, each specifying a field and direction.
Step 2: Match correct syntax
{ employees(orderBy: [{ department: ASC }, { salary: DESC }]) { id name department salary } } uses a list with two objects: first { department: ASC }, then { salary: DESC }, which is correct.
Step 3: Check other options
{ employees(orderBy: { department: ASC, salary: DESC }) { id name department salary } } uses a single object with two keys, which may not guarantee order. { employees(orderBy: [department: ASC, salary: DESC]) { id name department salary } } has invalid syntax. { employees(orderBy: { salary: DESC, department: ASC }) { id name department salary } } reverses sorting priority.
Final Answer:
{ employees(orderBy: [{ department: ASC }, { salary: DESC }]) { id name department salary } } -> Option B
Quick Check:
Multi-field orderBy = list of objects [OK]
Hint: Use a list of objects for multi-level sorting in orderBy [OK]
Common Mistakes:
Using a single object for multiple sort fields
Reversing the order of sorting priorities
Incorrect syntax for list of sorting fields
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.