how to design database for binary tree?

15,303

Solution 1

SQL Server 2008 has a built-in data-type called hierarchyid to store hierarchical information. Here are some pointers.

And of course you can do this as mentioned by arsenmkrt in databases other than sqlserver2008.

Solution 2

id | parentid | name
---------------------
 1 | null     | node1
 2 | 1        | node2
 3 | 1        | node3

Solution 3

This has been asked and answered before.

Here's a pretty decent tutorial which explains why adjacency model proposed by arsenmkrt is less than ideal.

Share:
15,303
anishMarokey
Author by

anishMarokey

Software Engineer @ MISYS -> INDIA. I love to spend most of my time in coding and reading blogs and books, related to microsoft technologies Love to solve problems in .Net My Lists Follow me on Twitter My MSDN My ASP

Updated on June 04, 2022

Comments

  • anishMarokey
    anishMarokey almost 2 years

    I'm doing a project in the field of multilevel marketing on .Net and SQL server. In the database it should save like a binary tree. How should i design a database?

  • Dave
    Dave almost 15 years
    Exercise: Write a query that returns all decedents from node1.
  • Arsen Mkrtchyan
    Arsen Mkrtchyan almost 15 years
    you mean this? select * From tab where parentid = (select id from table where name = 'node1')
  • ChssPly76
    ChssPly76 almost 15 years
    That's hilarious :-) However, you probably should have pointed out a better alternative, like using nested sets model.
  • Arsen Mkrtchyan
    Arsen Mkrtchyan almost 15 years
    +1 I didn't think about that before ;)
  • user3012759
    user3012759 over 7 years
    @ChssPly76 well, that's easy no? select * from tab where name != 'node1' ;) but seriously how does this answer have 3 upvotes?