title: MySQL SELECT Tree Parent IDs
body: <p>How can I sort the records of a SELECT statement so that they represent a valid tree?</p>
  
  <p>All of my attempts show sub-nodes nested under wrong parent nodes. What is the most reliable way to achieve this ordering?</p>
  
  <p><strong>Data</strong></p>
  
  <pre><code>ID      Parent ID      Title
  --------------------------------------------
  0       NULL           Root
  1       0              Node A
  2       0              Node B
  3       1              Sub-Node C
  4       1              Sub-Node D
  5       3              Sub-Node E
  </code></pre>
  
  <p><strong>Output</strong></p>
  
  <pre><code>ID      Parent ID      Title
  --------------------------------------------
  0       NULL           Root
  1       0              Node A
  3       1              Sub-Node C
  5       3              Sub-Node E
  4       1              Sub-Node D
  2       0              Node B
  </code></pre>
  
  <p><strong>Data Visualisation</strong></p>
  
  <pre><code>Root
      Node A
          Sub-Node C
              Sub-Node E
          Sub-Node D
      Node B
  </code></pre>