SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 19 / 37

Middle

How do you store a category tree in a database and fetch an entire subtree?

Short answer

The simplest way: each row has a parent_id pointing to its parent, and WITH RECURSIVE walks down the whole subtree. For trees read often and rarely changed, consider storing paths or a closure table.

new rows foundno new rowsAnchor: root rowruns onceRecursive part:JOIN children on parent_idReturn whole subtree

3 points to say:

  1. parent_id + WITH RECURSIVE is the default.
  2. Index parent_id, guard against cycles.
  3. Cache small trees in the application.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.