Query arguments in GraphQL - Time & Space Complexity
We want to understand how the time to run a GraphQL query changes when we use arguments to filter data.
How does adding arguments affect the work the server does?
Analyze the time complexity of the following code snippet.
query GetBooksByAuthor($authorName: String!) {
books(author: $authorName) {
id
title
author
}
}
This query fetches books filtered by the author's name using an argument.
Look for repeated steps in the query processing.
- Primary operation: Checking each book to see if the author matches the argument.
- How many times: Once for every book in the database.
As the number of books grows, the server checks more items to find matches.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of books.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the number of books increases.
[X] Wrong: "Using an argument makes the query run instantly no matter how many books there are."
[OK] Correct: The server still checks each book to see if it matches the argument, so more books mean more work.
Understanding how arguments affect query time helps you explain how filtering works behind the scenes, a useful skill in many real projects.
"What if the books were stored in a way that lets the server find authors quickly without checking each book? How would the time complexity change?"