title: SQL select descendants of a row
body: <p>Suppose a tree structure is implemented in SQL like this:</p>
  
  <pre><code>CREATE TABLE nodes (
      id INTEGER PRIMARY KEY,
      parent INTEGER -- references nodes(id)
  );
  </code></pre>
  
  <p>Although cycles can be created in this representation, let's assume we never let that happen.  The table will only store a collection of roots (records where parent is null) and their descendants.</p>
  
  <p>The goal is to, given an id of a node on the table, find all nodes that are descendants of it.</p>
  
  <p><strong>A</strong> is a descendant of <strong>B</strong> if either <strong>A</strong>'s parent is <strong>B</strong> or <strong>A</strong>'s parent is a descendant of <strong>B</strong>.  Note the recursive definition.</p>
  
  <p>Here is some sample data:</p>
  
  <pre><code>INSERT INTO nodes VALUES (1, NULL);
  INSERT INTO nodes VALUES (2, 1);
  INSERT INTO nodes VALUES (3, 2);
  INSERT INTO nodes VALUES (4, 3);
  INSERT INTO nodes VALUES (5, 3);
  INSERT INTO nodes VALUES (6, 2);
  </code></pre>
  
  <p>which represents:</p>
  
  <pre><code>1
  `-- 2
      |-- 3
      |   |-- 4
      |   `-- 5
      |
      `-- 6
  </code></pre>
  
  <p>We can select the (immediate) children of <code>1</code> by doing this:</p>
  
  <pre><code>SELECT a.* FROM nodes AS a WHERE parent=1;
  </code></pre>
  
  <p>We can select the children and grandchildren of <code>1</code> by doing this:</p>
  
  <pre><code>SELECT a.* FROM nodes AS a WHERE parent=1
  UNION ALL
  SELECT b.* FROM nodes AS a, nodes AS b WHERE a.parent=1 AND b.parent=a.id;
  </code></pre>
  
  <p>We can select the children, grandchildren, and great grandchildren of <code>1</code> by doing this:</p>
  
  <pre><code>SELECT a.* FROM nodes AS a WHERE parent=1
  UNION ALL
  SELECT b.* FROM nodes AS a, nodes AS b WHERE a.parent=1 AND b.parent=a.id
  UNION ALL
  SELECT c.* FROM nodes AS a, nodes AS b, nodes AS c WHERE a.parent=1 AND b.parent=a.id AND c.parent=b.id;
  </code></pre>
  
  <p>How can a query be constructed that gets all descendants of node <code>1</code> rather than those at a fixed depth?  It seems like I would need to create a recursive query or something.</p>
  
  <p>I'd like to know if such a query would be possible using SQLite.  However, if this type of query requires features not available in SQLite, I'm curious to know if it can be done in other SQL databases.</p>