 <p>The way I usually do this is by adding a <code>keychain</code> column. For your data:</p> <pre> ID PARENTID KEYCHAIN 1 NULL 1 2 1 1.2 3 1 1.3 4 1 1.4 5 2 1.2.5 6 2 1.2.6 7 3 1.3.7 8 3 1.3.8 9 4 1.4.9 10 9 1.4.9.10 </pre> <p>This column would obviously have to be calculated at insert using the generated id, but once it's in there you can write your query quite simply.</p> <pre><code>SELECT * FROM mytable WHERE KEYCHAIN like '1.2.%' or KEYCHAIN = '1.2' </code></pre> <p>There are probably other ways to do this, but I've found this method to work pretty well.</p>