Quick revision
The short answer
An adjacency list stores each category with a parent_id that references categories(id), indexed so children can be found quickly. A recursive CTE starts from the children of category 10 with depth 1 and repeatedly joins the next level, adding 1 to the depth, until no rows are left. We guard against cycles in bad data with the CYCLE clause of PostgreSQL 14 and later, or a path array; the model makes moves cheap but deep reads need recursion, and materialized paths, nested sets and closure tables are the alternatives.
What to remember
In this answer, we stored a category tree as an adjacency list with an indexed self-referencing parent_id, wrote a recursive CTE that returns every descendant of category 10 with its depth, and followed it round by round. We protected the query with the CYCLE clause or a path array, prevented cycles at write time by checking that the new parent is not in the subtree, and compared the adjacency list's cheap moves with the faster reads of materialized paths, nested sets and closure tables.
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 stores each category with a parent_id that references categories(id), indexed so children can be found quickly. A recursive CTE starts from the children of category 10 with depth 1 and repeatedly joins the next level, adding 1 to the depth, until no rows are left. We guard against cycles in bad data with the CYCLE clause of PostgreSQL 14 and later, or a path array; the model makes moves cheap but deep reads need recursion, and materialized paths, nested sets and closure tables are the alternatives.
Why this question is asked
Category trees, folder structures, comment threads and organisation charts are all hierarchies of unknown depth, and SQL tables are flat. Interviewers ask this coding question because it checks whether we can write a recursive query, which many developers rarely do, and whether we know what can go wrong with tree data. In this answer, we will build the table, walk through the recursive query one iteration at a time, protect it against cycles, prevent cycles from being created, and compare the adjacency list with the other common tree models.
1A Quick Recap of the Adjacency List
An adjacency list is the simplest way to store a tree: each row points to its parent. The root rows have no parent, so parent_id is null for them. The foreign key from parent_id back to the same table ensures every parent exists.
The index on parent_id matters because every step of a tree walk asks 'which rows have this parent?'. Without it, each level of the recursion scans the whole table. PostgreSQL does not create indexes on foreign key columns automatically, so we add it ourselves.
2Writing the Recursive Query
A recursive common table expression (CTE) has two parts joined by UNION ALL. The anchor part runs once and produces the starting rows. The recursive part refers to the CTE itself and runs again and again, each time using only the rows produced by the previous round, until a round produces nothing.
| Round | Input rows | New rows produced |
|---|---|---|
| Anchor | categories with parent_id = 10 | 11 (depth 1), 12 (depth 1) |
| 1 | 11, 12 | 13 (depth 2), child of 11 |
| 2 | 13 | 14 (depth 3) |
| 3 | 14 | none, so the recursion stops |
Notice that category 10 itself is not in the result, because the anchor starts from its children. If we want to include it with depth 0, the anchor becomes WHERE id = 10 with 0 AS depth.
3Guarding Against Cycles in Bad Data
If bad data ever creates a loop, say 13 has parent 14 and 14 has parent 13, the recursive part keeps producing rows forever, and the query runs until it fails or someone cancels it. PostgreSQL 14 added a CYCLE clause that detects this for us.
CYCLE id tells PostgreSQL to remember the ids visited on each branch, in an array column named path, and to mark a row with is_cycle = true when an id repeats, without recursing further from it. The manual version does the same thing: it carries the path along and refuses to visit an id already on it. A depth limit, such as WHERE t.depth < 50, is a cruder but simple safety net.
4Preventing a Category From Becoming Its Own Ancestor
Detecting cycles in queries is a safety net; the real fix is not letting them be written. The CHECK (parent_id <> id) above stops the direct case. For deeper loops, the move operation must check that the new parent is not inside the subtree being moved.
The application runs this check and the UPDATE in one transaction, ideally after locking the rows involved, or a trigger runs it on every parent_id change. Without the check, two concurrent moves can still create a loop, so locking or a serializable transaction matters for busy trees.
5Trade-offs and Alternatives
The adjacency list's strength is cheap writes: moving a whole subtree is one UPDATE of one parent_id. Its weakness is that reading a deep subtree or a full path to the root needs a recursive query, which is a few index lookups per level. For category trees of a few thousand rows that is fast enough, and it is the right default.
| Model | Read subtree | Move subtree | Notes |
|---|---|---|---|
| Adjacency list | Recursive CTE | One update | Simple, the default |
| Materialized path (ltree) | Prefix match, indexed | Rewrite paths in subtree | Path like 1.10.11 |
| Nested sets | One range query | Renumber much of the tree | Fast reads, costly writes |
| Closure table | One indexed join | Rows per ancestor pair | Fast both ways, more storage |
A materialized path stores the full path in each row, and PostgreSQL's ltree extension indexes it so 'all descendants of 1.10' is an indexed lookup. Nested sets give each node left and right numbers so a subtree is a numeric range, which reads fast but makes inserts renumber many rows. A closure table stores every ancestor and descendant pair with its depth, making both directions a single join at the cost of extra rows. We choose one of these only when reads of deep trees are proven to be the bottleneck.
6Follow-up questions
How would you prevent a category from becoming its own ancestor?
A CHECK (parent_id <> id) blocks the direct case. For indirect loops, every move must verify, with a recursive query over the subtree of the category being moved, that the new parent is not one of its descendants, and do that check and the update in one transaction with the affected rows locked. A trigger on parent_id updates can enforce this for all writers, not just the application.
How do you get the path from a category up to the root?
Reverse the direction of the join: the anchor selects the category itself, and the recursive part joins categories p ON p.id = t.parent_id, walking up until parent_id is null. Each round adds one ancestor, and ordering by depth descending gives the breadcrumb from the root down.
Is UNION instead of UNION ALL a cycle guard?
Partly. UNION removes duplicate rows, so if a cycle produces exactly the same row again, recursion stops. But our rows carry a depth that increases each round, so a revisited id comes back as a different row and the loop continues. The CYCLE clause or a path array is the reliable guard.
7Conclusion
In this answer, we stored a category tree as an adjacency list with an indexed self-referencing parent_id, wrote a recursive CTE that returns every descendant of category 10 with its depth, and followed it round by round. We protected the query with the CYCLE clause or a path array, prevented cycles at write time by checking that the new parent is not in the subtree, and compared the adjacency list's cheap moves with the faster reads of materialized paths, nested sets and closure tables.
Open with
I would create categories with id as the primary key, parent_id as a nullable foreign key to categories id, a not null name, and a check that parent_id is not equal to id.
Then, if they want more
Then an index on parent_id, because every step of a tree walk looks up children by parent, and PostgreSQL does not index foreign keys automatically. For the descendants I would write a recursive CTE. The anchor selects the categories whose parent_id is 10, with depth 1.
The recursive part joins categories to the CTE on parent_id equals the previous round's id and adds one to the depth. PostgreSQL keeps running the recursive part on the rows from the last round until it gets nothing back, so the result is every descendant with its level.
To be safe against bad data, I would add the CYCLE clause, available since PostgreSQL 14, which tracks visited ids and stops at a repeat, or on older versions carry a path array and skip ids already in it.
To prevent cycles in the first place, a move checks that the new parent is not inside the moved subtree, in the same transaction. The adjacency list makes moves one update, but deep reads need recursion. If reads became the bottleneck, I would look at ltree materialized paths, nested sets for read-heavy static trees, or a closure table.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 14
- 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, MySQL reference manual
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 "Model a category tree of unlimited depth in PostgreSQL with an adjacency list, and write...": https://scrivio-interview-library.netlify.app/databases/data-modeling/b478e2b080/