SQL database resolvers in GraphQL - Time & Space Complexity
When using SQL database resolvers in GraphQL, it's important to understand how the time to get data grows as the data size grows.
We want to know how the number of database calls and data processing steps increase when we ask for more or bigger data.
Analyze the time complexity of the following GraphQL resolver code that fetches data from an SQL database.
query GetUsersWithPosts {
users {
id
name
posts {
id
title
}
}
}
This query fetches a list of users and for each user, it fetches their posts from the database.
Look for repeated database calls or loops in the resolver process.
- Primary operation: Fetching posts for each user, often done with one query per user.
- How many times: Once for each user in the users list.
As the number of users grows, the number of post-fetching operations grows too.
| Input Size (n users) | Approx. Operations (queries) |
|---|---|
| 10 | 1 (users) + 10 (posts queries per user) = 11 |
| 100 | 1 + 100 = 101 |
| 1000 | 1 + 1000 = 1001 |
Pattern observation: The number of operations grows roughly in a straight line with the number of users.
Time Complexity: O(n)
This means the time to get all users and their posts grows directly in proportion to the number of users.
[X] Wrong: "Fetching posts for all users is just one database call, so time stays the same no matter how many users."
[OK] Correct: Usually, fetching posts for each user requires separate calls or processing, so time grows with the number of users.
Understanding how database resolvers scale helps you write efficient queries and explain your choices clearly in interviews.
"What if we changed the resolver to fetch all posts for all users in a single query? How would the time complexity change?"