Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store directory / hierarchy / tree structure in the database?

How do i store a directory / hierarchy / tree structure in the database? Namely MSSQL Server.

@olavk: Doesn't look like you've seen my own answer. The way i use is way better than recursive queries :)

p.p.s. This is the way to go!

like image 900
roman m Avatar asked Sep 27 '08 19:09

roman m


People also ask

How do you store a tree structure in a 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.

What is the best database to store hierarchical data?

Graph database are ideal for complex hierarchical data.

Which database is best for tree structure?

Database type Unless you're aiming at huge amounts of data I suggest you go with any of the SQL databases that you know best (MSSQL, MySQL, Oracle). But if your database will contain enormous number of hierarchy nodes then flirting with a specialised graph-oriented database may be a better option.

How do you create a hierarchy in SQL?

Select the data, adding a column that converts the Level data into a text value that is easy to understand. This query also orders the result by the hierarchyid data type. SELECT CAST(Level AS nvarchar(100)) AS [Converted Level], * FROM SimpleDemo ORDER BY Level; Here is the result set.


1 Answers

There are many ways to store hierarchies in SQL databases. Which one to choose depends on which DBMS product you use, and how the data will be used. As you have used the MSSQL2005 tag, I think you should start considering the "Adjacency List" model; if you find that it doesn't perform well for your application, then have a look at Vadim Tropashko's comparison which highlights differences between models with a focus on multiple performance characteristics.

like image 85
Troels Arvin Avatar answered Sep 19 '22 04:09

Troels Arvin