title: How to automatically break down a SQL-like query with many joins into discrete, independent steps?
body: <p><em>Note: This is a learning exercise to learn how to implement a SQL-like relational database. This is just one thin slice of a question in the overall grand vision.</em></p>
  <p>I have the following query, given a test database with a few hundred records:</p>
  <pre><code>select distinct &quot;companies&quot;.&quot;name&quot;
  from &quot;companies&quot;
  inner join &quot;projects&quot; on &quot;projects&quot;.&quot;company_id&quot; = &quot;companies&quot;.&quot;id&quot;
  inner join &quot;posts&quot; on &quot;posts&quot;.&quot;project_id&quot; = &quot;projects&quot;.&quot;id&quot;
  inner join &quot;comments&quot; on &quot;comments&quot;.&quot;post_id&quot; = &quot;posts&quot;.&quot;id&quot;
  inner join &quot;addresses&quot; on &quot;addresses&quot;.&quot;company_id&quot; = &quot;companies&quot;.&quot;id&quot;
  where &quot;addresses&quot;.&quot;name&quot; = 'Address Foo'
  and &quot;comments&quot;.&quot;message&quot; = 'Comment 3/3/2/1';
  </code></pre>
  <p>Here, the query is kind of unrealistic, but it demonstrates the point which I am trying to make. The point is to have a query with a few joins, so that I can figure out how to write this in sequential steps.</p>
  <p>The first part of the question is (which I think I've partially figured out), is how do you write these joins as a sequence of independent steps, with the output of one fed into the input of the other? Also, is there more than one way to do it?</p>
  <pre><code>// step 1
  let companies = select('companies')
  // step 2
  let projects = join(companies, select('projects'), 'id', 'company_id')
  // step 3
  let posts = join(projects, select('posts'), 'id', 'project_id')
  // step 4
  let comments = join(posts, select('comments'), 'id', 'post_id')
  // step 5
  let finalPosts = posts.filter(post =&gt; !!comments.find(comment =&gt; comment.post_id === post.id))
  // step 6
  let finalProjects = projects.filter(project =&gt; !!posts.find(post =&gt; post.project_id === project.id))
  
  // step 7, could also be run in parallel to step 2 potentially
  let addresses = join(companies, select('addresses'), 'id', 'company_id')
  
  // step 8
  let finalCompanies = companies.filter(company =&gt; {
    return !!posts.find(post =&gt; post.company_id === company.id)
      &amp;&amp; !!addresses.find(address =&gt; address.company_id === company.id)
  })
  </code></pre>
  <p>These filters could probably be more optimized using indexes of some sort, but that is beside the point I think. This just demonstrates that there seem to be about 8 steps to find the companies we are looking for.</p>
  <p>The main question is, how do you <em>automatically figure out the steps from the SQL query?</em></p>
  <p>I am not asking about how to parse the SQL query into an AST. Assume we have some sort of object structure we are dealing with, like an AST, to start.</p>
  <p>How would you have to have the SQL query in structured object form, such that it would lead to these 8 steps? I would like to be able to specify a query (using a custom JSON-like syntax, not SQL), and then have it divide the query into these steps to divide and conquer so to speak and perform the queries in parts (for learning how to implement distributed databases). But I don't see how we go from SQL-like syntax, to 8 steps. Can you show how that might be done?</p>
  <p><a href="https://gist.github.com/lancejpollard/6164b124fe021ad3d3db25a8c331a063" rel="nofollow noreferrer">Here is the full code</a> for the demo, which you can run with <code>psql postgres -f test.sql</code>. The result should be &quot;Company 3&quot;.</p>
  <p>Basically looking for a high level algorithm (doesn't even need to be code), which describes the key way you would break down some sort of AST-like object representation of a SQL query, into the actual planned steps of the query.</p>
  <p>My algorithm looks like this in my head:</p>
  <ol>
  <li>represent SQL query in object tree.</li>
  <li>convert object tree to steps.</li>
  </ol>
  <p>I am not really sure what (1) should be structured like, and even if we had some sort of structure, I'm not sure how to get that to complete (2). Looking for more details on the implementations of these steps, mainly step (2).</p>
  <p>My &quot;object structure&quot; for step 1 would be something like this:</p>
  <pre><code>const query = {
    select: {
      distinct: true,
      columns: ['companies.name'],
      from: ['companies'],
    },
    joins: [
      {
        type: 'inner join',
        table: 'projects',
        left: 'projects.company_id',
        right: 'companies.id',
      },
      ...
    ],
    conditions: [
      {
        left: 'addresses.name',
        op: '=',
        right: 'Address Foo'
      },
      ...
    ]
  }
  </code></pre>
  <p>I am not sure how useful that is, but it doesn't relate to steps at all. At a high level, what kind of code would I have to write to convert that object sort of structure into steps? Seems like one potential avenue is do a topological sort on the joins. But then you need to combine that with the select and conditions somehow, not sure how you would even begin to programmatically know what step should be before what other step, or even what the steps are. Maybe if I somehow could break it into known &quot;chunks&quot;, then it would be simple to apply TOP sort to it after that, but then the question is still, how to get into chunks from the object structure / SQL?</p>
  <p>Basically, I have been reading about the theory behind &quot;query planning and optimization&quot;, but don't know how to apply it in this regard. How did <a href="http://www.grammaticalframework.org/qconv/qconv-a.html" rel="nofollow noreferrer">this site</a> do it?</p>
  <p><a href="https://i.stack.imgur.com/vQbVl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vQbVl.png" alt="enter image description here" /></a></p>
  <p>One aspect is breaking at least the <code>where</code> conditions into <a href="https://stackoverflow.com/a/7994272/169992">CNF</a>.</p>