What would be the best way to implement a customizable tree data structure (meaning, a tree structure with an unknown number of level) in a database?
I've done this once before using a table with a foreign key to itself.
What other implementations could you see, and does this implementation make sense?
This question is related to
sql
database-design
tree
If you have to use Relational DataBase to organize tree data structure then Postgresql has cool ltree module that provides data type for representing labels of data stored in a hierarchical tree-like structure. You can get the idea from there.(For more information see: http://www.postgresql.org/docs/9.0/static/ltree.html)
In common LDAP is used to organize records in hierarchical structure.
Have a look at Managing Hierarchical Data in MySQL. It discusses two approaches for storing and managing hierarchical (tree-like) data in a relational database.
The first approach is the adjacency list model, which is what you essentially describe: having a foreign key that refers to the table itself. While this approach is simple, it can be very inefficient for certain queries, like building the whole tree.
The second approach discussed in the article is the nested set model. This approach is far more efficient and flexible. Refer to the article for detailed explanation and example queries.
Having a table with a foreign key to itself does make sense to me.
You can then use a common table expression in SQL or the connect by prior statement in Oracle to build your tree.
If anyone using MS SQL Server 2008 and higher lands on this question: SQL Server 2008 and higher has a new "hierarchyId" feature designed specifically for this task.
More info at https://docs.microsoft.com/en-us/sql/relational-databases/hierarchical-data-sql-server
Source: Stackoverflow.com