Assuming your only concern is selects and not inserts/updates/deletes, this depends on needs, such as:
- do you need to know what level each node is at?
- do you need to know if each node has any children while rendering it?
- do you need to sort siblings by name?
However, if there really are minimal changes to the tree being done, then it almost doesn't matter what scheme you use, as you can do all the work in the application layer and cache the output.
Edit:
When order matters, I usually go for the materialized path method, and add an additional column SortPath. This way you can get your results sorted by sibling, which is a denormalization that makes rendering the tree in HTML extremely easy, as you can write out the entire tree (or any portion) in exactly the order you receive the records using a single query. This is optimal for speed, and is the easiest way to sort more than one level at a time.
E.g.,
CREATE TABLE [dbo].[MatPath](
[ID] [int] NULL,
[Name] [varchar](50) NULL,
[Path] [varchar](max) NULL,
[SortPath] [varchar](max) NULL
)
insert into MatPath (ID, Name, Path, SortPath) values (1, 'Animal', '1', 'Animal-1')
insert into MatPath (ID, Name, Path, SortPath) values (2, 'Dog', '1.2', 'Animal-1|Dog-2')
insert into MatPath (ID, Name, Path, SortPath) values (3, 'Horse', '1.3', 'Animal-1|Horse-3')
insert into MatPath (ID, Name, Path, SortPath) values (4, 'Beagle', '1.2.4', 'Animal-1|Dog-2|Beagle-4')
insert into MatPath (ID, Name, Path, SortPath) values (5, 'Abyssinian', '1.3.5', 'Animal-1|Horse-3|Abyssinian-5')
insert into MatPath (ID, Name, Path, SortPath) values (6, 'Collie', '1.2.6', 'Animal-1|Dog-2|Collie-6')
select *
from MatPath
order by SortPath
Output:
ID Name Path SortPath
------ --------------- ----------- --------------------------------
1 Animal 1 Animal-1
2 Dog 1.2 Animal-1|Dog-2
4 Beagle 1.2.4 Animal-1|Dog-2|Beagle-4
6 Collie 1.2.6 Animal-1|Dog-2|Collie-6
3 Horse 1.3 Animal-1|Horse-3
5 Abyssinian 1.3.5 Animal-1|Horse-3|Abyssinian-5
(6 row(s) affected)
You can determine the level of each node by counting pipes (or periods) in the application layer, or in SQL using whatever built-int or custom functions that can count occurrences of a string.
Also, you'll notice I append the ID
to the Name
when building SortPath
. This is to ensure that two sibling nodes with the same name will always get returned in the same order.