Quick revision
The short answer
An adjacency list (parent_id) is the simplest to write but needs a recursive query for every subtree. A closure table stores every ancestor-descendant pair, so 'all products under a category' becomes one indexed join, at the price of extra rows and extra work on moves. A materialised path such as PostgreSQL's ltree answers subtree queries with an indexed prefix test, but moving a subtree rewrites every path in it, and nested sets read fast but make inserts and moves rewrite large parts of the table. For a catalogue that is read far more than it changes, I would recommend a closure table, or ltree on PostgreSQL, keeping parent_id as the source of truth.
What to remember
In this answer, we saw that the adjacency list is simple but needs recursion for subtrees, that a closure table turns subtree reads into one join by storing every ancestor-descendant pair, that ltree answers them with an indexed prefix test but rewrites paths on moves, and that nested sets read fast but make common inserts expensive. With reads vastly outnumbering changes, we chose ltree or a closure table, kept parent_id as the source of truth, and added a rebuild check.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
An adjacency list (parent_id) is the simplest to write but needs a recursive query for every subtree. A closure table stores every ancestor-descendant pair, so 'all products under a category' becomes one indexed join, at the price of extra rows and extra work on moves. A materialised path such as PostgreSQL's ltree answers subtree queries with an indexed prefix test, but moving a subtree rewrites every path in it, and nested sets read fast but make inserts and moves rewrite large parts of the table. For a catalogue that is read far more than it changes, I would recommend a closure table, or ltree on PostgreSQL, keeping parent_id as the source of truth.
Why this question is asked
Category trees look harmless until the most common query on the site, 'show every product in Electronics and all its subcategories', becomes a recursive query that runs on every page view. Interviewers ask this at senior level because there is no single right model: each one moves cost between reads, writes, storage and complexity, and the right choice depends on numbers we should ask for. In this answer, we will recap the four models, show the subtree query and the move operation for each, compare them side by side, and then walk through a recommendation for a realistic catalogue.
1A Quick Recap of the Problem
Our catalogue has a categories table with id, name and parent_id, and a products table with a category_id. A subtree is a category plus all of its descendants, at any depth. The business question is almost always a subtree question: list products under Electronics, count products under Phones, build breadcrumbs from a leaf back to the root.
Let us use concrete numbers to reason with. Say there are 20,000 categories, the tree is at most 7 levels deep with an average depth of 4, there are 2 million products, the subtree query runs about 300 times per second, and merchandisers change the tree a few dozen times a day, mostly adding leaves and occasionally moving a branch. Those numbers already lean towards a read-optimised model.
2Adjacency List: What We Have Today
The adjacency list is the parent_id column itself. Inserting, deleting and moving are single-row updates: to move Phones under Mobile, we change one parent_id. Reading a subtree needs WITH RECURSIVE, which walks one level per round.
With an index on parent_id this is not terrible, maybe a few milliseconds for a medium subtree, but it is a loop the planner cannot estimate well, so the join to products often gets a poor plan. And it is awkward to write in JPA, which is part of why the team calls it complex. The adjacency list is still the best source of truth: every other model can be derived from it.
3Closure Table: Every Ancestor-Descendant Pair
A closure table, category_paths(ancestor_id, descendant_id, depth), stores one row for each pair where one category is above another, including a row of depth 0 from each category to itself. The subtree query becomes a plain join, which every ORM and every planner handles well.
The storage cost is the number of rows times the average depth plus one, so about 20,000 x 5 = 100,000 rows here, which is tiny. Moving a subtree is the expensive part: we delete the pairs that link the moved nodes to their old ancestors and insert pairs to the new ones, which touches subtree size times ancestor count rows. For a branch of 500 categories that is a few thousand rows in one transaction, fine a few times a day.
4Materialised Path and ltree
A materialised path stores each category's full path from the root as a value, such as 1.10.42 for root, Electronics, Phones. PostgreSQL's ltree extension gives this a proper type, operators and index support: the <@ operator means 'is a descendant of', and a GiST index makes it fast.
Notice that we build the path from ids, not names, so renaming a category changes nothing. The read is a single indexed condition and the breadcrumb is in the row itself. The cost is on moves: every row in the branch gets a new path, so moving a branch of 500 categories updates 500 rows. That is the same order as the closure table, and simpler to reason about. The label rules for ltree are restrictive (letters, digits and underscores, with newer releases allowing more; check your version), which is another reason to use numeric ids.
5Nested Sets: Fast Reads, Painful Writes
Nested sets give each category a left and a right number from a depth-first walk of the tree, so that every descendant's numbers fall between its ancestor's. A subtree is then a range: lft BETWEEN 20 AND 75. Reads are excellent and need only a B-tree index.
But there is a catch: inserting one category in the middle shifts the left and right numbers of every node after it in the walk, on average half the table. With 20,000 categories that is about 10,000 row updates, and they all lock the same rows, so concurrent edits by merchandisers serialise or deadlock. Nested sets suit trees that are built once and rarely change, such as a fixed taxonomy loaded nightly, and rarely suit a catalogue that people edit during the day.
| Model | Subtree read | Insert a leaf | Move a branch | Extra storage |
|---|---|---|---|---|
| Adjacency list | Recursive CTE, one round per level | 1 row | 1 row | None |
| Closure table | One indexed join | Depth + 1 rows | Subtree x ancestors rows | About N x depth rows |
| ltree path | Indexed <@ prefix test | 1 row | Every row in the branch | One path per row |
| Nested sets | Range on lft/rgt | About half the table | About half the table | Two ints per row |
6Choosing for This Catalogue
The decision turns on three numbers: how often we read subtrees, how often the tree changes, and how deep it is. Here reads outnumber changes by roughly a million to one, the tree is shallow, and changes are mostly new leaves. That rules out nested sets, whose inserts are the most common write and the most expensive. It makes staying with a pure adjacency list hard to justify for a query on every page view.
Between the remaining two, I would pick ltree on PostgreSQL when the team is comfortable with an extension, because the path also gives breadcrumbs and sorting for free and the move is a single UPDATE. I would pick a closure table when the database is MySQL or when portability matters, because it is plain tables and joins. In both cases I keep parent_id as the source of truth, maintain the derived structure in the same transaction as the change, and add a nightly job that rebuilds it from parent_id and compares, so a bug in the maintenance code is caught within a day. Finally, if the hot query is 'products under a category', a cache of category id to descendant ids, invalidated on tree changes, can remove the database work entirely for most requests.
7Follow-up questions
How do you keep the closure table consistent with parent_id?
The safest way is to change both in one transaction in the service that owns the tree: update parent_id, then delete and insert the affected closure rows. Database triggers can do the same and catch changes from scripts, at the cost of logic that is harder to see and test. Whichever we choose, a periodic job that rebuilds the closure from parent_id with a recursive CTE and reports differences gives us a safety net, and the same job can repair the table.
Is ltree's prefix query really faster than the recursive CTE?
For a subtree read on a hot path, usually yes, because it is one indexed condition that the planner can estimate, instead of a loop whose row count it has to guess. The difference grows with depth and with how the result is joined to other tables, since a better estimate leads to a better join plan. We should still measure with EXPLAIN ANALYZE on realistic data, because for a tiny tree both are fast and the extra model may not be worth it.
What about deep trees, such as folders with thousands of levels?
Depth changes the picture. Closure table storage grows with depth, and an ltree path grows in length with every level, so both get heavier. For very deep trees the adjacency list with a recursive CTE, or a path stored as an array of ids, may be the more practical choice, and we would push hard on whether the product really needs whole-subtree queries at that depth.
8Conclusion
In this answer, we saw that the adjacency list is simple but needs recursion for subtrees, that a closure table turns subtree reads into one join by storing every ancestor-descendant pair, that ltree answers them with an indexed prefix test but rewrites paths on moves, and that nested sets read fast but make common inserts expensive. With reads vastly outnumbering changes, we chose ltree or a closure table, kept parent_id as the source of truth, and added a rebuild check.
Open with
I would start by asking for the numbers: how many categories, how deep, how often the subtree query runs and how often the tree changes. Say 20,000 categories, depth 7, hundreds of reads per second, a few dozen edits a day.
Then, if they want more
The adjacency list we have, parent_id, is the easiest to write to, one row per change, but every subtree read needs a recursive CTE, which is hard to plan well and awkward in JPA. A closure table stores every ancestor-descendant pair with a depth.
The subtree becomes one indexed join, storage is about the number of categories times average depth, so around 100,000 rows here, and a move rewrites the pairs between the moved branch and its old and new ancestors.
A materialised path, which on PostgreSQL I would do with ltree, stores the path of ids and answers the subtree with the descendant operator on a GiST index, and a move rewrites every path in the branch. Nested sets make reads a simple range, but an insert renumbers about half the table, so they only fit trees that rarely change.
For this catalogue I would choose ltree on PostgreSQL, or a closure table if we need portability. Either way, parent_id stays the source of truth, the derived structure is updated in the same transaction, and a nightly job rebuilds and compares it to catch bugs.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A product catalogue stores categories as a self-referencing parent_id table, and queries...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/ca4ffb28e4/