title: How do I sort a linked list in sql?
body: <p>I have implemented a linked list as a self-referencing database table:</p>
  
  <pre><code>CREATE TABLE LinkedList(
      Id bigint NOT NULL,
      ParentId bigint NULL,
      SomeData nvarchar(50) NOT NULL) 
  </code></pre>
  
  <p>where Id is the primary key, and ParentId is the Id of the previous node on the list. The first node has ParentId = NULL.</p>
  
  <p>I now want to SELECT from the table, sorting the rows in the same order they should appear, as nodes on the list.</p>
  
  <p>Eg.: if the table contains the rows</p>
  
  <pre><code>Id      ParentId  SomeData
  24971   NULL      0
  38324   24971     1
  60088   60089     3
  60089   38324     2
  61039   61497     5
  61497   60088     4
  109397  109831    7
  109831  61039     6
  </code></pre>
  
  <p>Then sorting it, using the criteria, should result in:</p>
  
  <pre><code>Id      ParentId  SomeData
  24971   NULL      0
  38324   24971     1
  60089   38324     2
  60088   60089     3
  61497   60088     4
  61039   61497     5
  109831  61039     6
  109397  109831    7
  </code></pre>
  
  <p>You're supposed to use the <em>SomeData</em> colum as a control, so please don't cheat doing  <em>ORDER by SomeData</em> :-)</p>