Optimized SQL for tree structures

It really depends on how you are going to access the tree.

One clever technique is to give every node a string id, where the parent’s id is a predictable substring of the child. For example, the parent could be ’01’, and the children would be ‘0100’, ‘0101’, ‘0102’, etc. This way you can select an entire subtree from the database at once with:

SELECT * FROM treedata WHERE id LIKE '0101%';

Because the criterion is an initial substring, an index on the ID column would speed the query.

Leave a Comment