Simon Willison’s Weblog

Subscribe

Storing trees in a database

19th June 2003

SitePoint: Storing Hierarchical Data in a Database, by Gijs Van Tulder. The article first shows how the easy way of storing hierarchies in a database, using parent fields and a recursive PHP function to iterate up the tree. It then goes on to talk about a far more interesting alternative called “Modified Preorder Tree Traversal” where trees are first “flattened” in to a heap-like structure, then each node is stored with a pair of numbers representing that node’s position in the tree. I’d seen this somewhere before but Gijs Van Tulder’s explanation is far clearer, and comes with some good examples showing how this unconventional storage method can retrieve all of the eventual children of a node in a single query. He also talks about ways of updating the tree structure when new items are added.

This is Storing trees in a database by Simon Willison, posted on 19th June 2003.

Next: Quick testing of alt attributes

Previous: Thunderbird supports extensions

Previously hosted at http://simon.incutio.com/archive/2003/06/19/storingTrees