Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a tree in SQL database

Tags:

I have to store a tree in a database, so what is the best way to do this? Show the method you use and name its pros and cons. (I am using SQL Server 2005)

like image 500
kalan Avatar asked Jul 09 '10 13:07

kalan


People also ask

How can we store tree in database?

The standard method of storing hierarchical data is simple parent-child relationship. Each record in the database includes a —parent id—, and a recursive query through the records build the children, siblings, and levels of the tree.

How do you represent a tree in a database?

You could use adjacency lists (your current idea), nested sets, or even (with appropriate database support) arrays of node ids to represent the path from the root. Which representation you choose depends on what you need to do to your data. @Kim, why array? If the graph is a tree, each node has at most one parent.

How we can store tree in database and how can we retrieve it back?

An alternative method to allow us to retrieve the entire tree is to have an extra column that identifies the tree to which each node belongs. This could be the ID of the root node, or some other identifier for the entire tree. This means that our table gains an extra column, so we're storing more data.


1 Answers

I found the discussion in the SQL Anti-patterns very helpfull, as it also focuses on the drawbacks of every implementation.

Also, The slides 48-77 in this presentation reiterate that analisys.

Bottom line, there is no such thing as a generic tree, and no silver bullet for SQL trees. You'll have to ask yourself about the data, how and how much will they be selected, modified, will branches be moved around, etc, and based on those answers implement a suitable solution.

like image 178
SWeko Avatar answered Jan 01 '23 05:01

SWeko