IT lexicon › Database › Nested set

Nested set

Database På svenska → Updated: 2026-05-29

A tree model where each node gets two numbers — a left and a right value — assigned by "walking around" the tree. A subtree then becomes a simple interval: a node's descendants all have left/right values within the node's own. Fast reads, expensive changes.

Mechanic: you traverse the tree in preorder and number each node when you "go down" (left) and "go up" (right). Win: "fetch the whole subtree" becomes WHERE lft BETWEEN node.lft AND node.rgt — a single fast interval query without recursion, and you can count descendants with pure arithmetic. Price: inserting or moving a node requires renumbering large parts of the tree (all nodes with higher values must be shifted) → very expensive with frequent changes. Best for read-heavy, rarely changed hierarchies (a category tree in a store). More complex than adjacency list but faster for subtree reads. A closure table gives a middle ground. Related to materialized path and closure table.

← Back to the lexicon