Note that there are some explanatory texts on larger screens.

plurals
  1. POManaging hierarchies in SQL: MPTT/nested sets vs adjacency lists vs storing paths
    primarykey
    data
    text
    <p>For a while now I've been wrestling with how best to handle hierarchies in SQL. Frustrated by the limitations of adjacency lists and the complexity of MPTT/nested sets, I began thinking about simply storing key paths instead, as a simple <code>node_key/node_key/...</code> string. I decided to compile the pros and cons of the three techniques:</p> <h3>Number of calls required to create/delete/move a node:</h3> <ul> <li>Adjacency = 1</li> <li>MPTT = 3</li> <li>Path = 1 (Replace old node path with new node path across all nodes that contain that path)</li> </ul> <h3>Number of calls required to get a tree:</h3> <ul> <li>Adjacency = [number of sub-levels]</li> <li>MPTT = 1</li> <li>Path = 1</li> </ul> <h3>Number of calls required to get path to a node / ancestry:</h3> <ul> <li>Adjacency = [number of super-levels]</li> <li>MPTT = 1</li> <li>Path = 0</li> </ul> <h3>Number of calls required to get number of subnodes:</h3> <ul> <li>Adjacency = [number of sub-levels] </li> <li>MPTT = 0 (Can be calculated from right/left values) </li> <li>Path = 1</li> </ul> <h3>Number of calls required to get depth of node:</h3> <ul> <li>Adjacency = [number of super-levels]</li> <li>MPTT = 1</li> <li>Path = 0</li> </ul> <h3>DB fields required:</h3> <ul> <li>Adjacency = 1 (parent)</li> <li>MPTT = 3 (parent,right,left)</li> <li>Path = 1 (path)</li> </ul> <h1>Conclusion</h1> <p>The stored path technique uses the same or less calls than the other techniques in every use case except one. By this analysis, storing paths is a clear winner. Not to mention, it's a lot simpler to implement, human readable, etc. </p> <p>So the question is, shouldn't stored paths be considered a stronger technique than MPTT? Why are stored paths not a more commonly used technique, and why would you not use them over MPTT in a given instance? </p> <p>Also, if you think this analysis is incomplete please let me know.</p> <h3>UPDATE:</h3> <p>Here are at least 2 things MPTT can do out of the box that a stored path solution won't:</p> <ol> <li>Allows calculation of subnode count for each node without any additional queries (mentioned above).</li> <li>Imposes an order on nodes at a given level. The other solutions are unordered.</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload