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.
3 points to say:
parent_id+WITH RECURSIVEis the default.- Index
parent_id, guard against cycles. - 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.