title: How many SQL database calls are made when you do a deeply nested GraphQL query?
body: <p>I know with GraphQL you are to implement the <a href="https://www.wisdomgeek.com/development/web-development/graphql/resolving-nested-queries-graphql/" rel="nofollow noreferrer">backend handlers</a> for the queries. So if you are using PostgreSQL, you might have a query like this:</p>
  <pre><code>query {
    authors {
      id
      name
      posts {
        id
        title
        comments {
          id
          body
          author {
            id
            name
          }
        }
      }
    }
  }
  </code></pre>
  <p>The naive solution would be to do something like this:</p>
  <pre><code>const resolvers = {
    Query: {
      authors: () =&gt; {
        // somewhat realistic sql pseudocode
        return knex('authors').select('*')
      },
    },
    Author: {
      posts: (author) =&gt; {
        return knex('posts').where('author_id', author.id)
      },
    },
    Post: {
      comments: (post) =&gt; {
        return knex('comments').where('post_id', post.id)
      },
    },
  };
  </code></pre>
  <p>However, this would be a pretty big problem. It would do the following essentially:</p>
  <ol>
  <li>Make 1 query for all authors.</li>
  <li>For each authors, make query for all posts. (n + 1 query)</li>
  <li>For each post, make query for all comments. (n + 1 query)</li>
  </ol>
  <p>So it's like a fanning out of queries. If there were 20 authors, each with 20 posts, that would be 21 db calls. If each post had 20 comments, that would be 401 db calls! 20 authors resolves 400 posts, which resolves 8000 comments, not like this is a real way you would do it, but to demonstrate the point. 1 -&gt; 20 -&gt; 400 db calls.</p>
  <p>If we add the <code>comments.author</code> calls, that's another 8000 db calls (one for each comment)!</p>
  <p>How would you batch this into let's say 3 db calls (1 for each type)? Is that what optimized GraphQL query resolvers do essentially? Or what is the best that can be done for this situation?</p>