Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Model a category tree of unlimited depth in PostgreSQL with an adjacency list, and write a query that returns all descendants of category 10 with their depth.

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.

SQL
CREATE TABLE categories (
id bigint PRIMARY KEY,
parent_id bigint REFERENCES categories(id),
name text NOT NULL,
CHECK (parent_id <> id) -- a category cannot be its own parent
);
CREATE INDEX categories_parent_id_idx ON categories (parent_id);
INSERT INTO categories VALUES
(1, NULL, 'All'),
(10, 1, 'Electronics'),
(11, 10, 'Phones'),
(12, 10, 'Laptops'),
(13, 11, 'Android phones'),
(14, 13, 'Rugged phones');

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.

SQL
WITH RECURSIVE tree AS (
SELECT id, parent_id, name, 1 AS depth -- anchor: direct children of 10
FROM categories
WHERE parent_id = 10
UNION ALL
SELECT c.id, c.parent_id, c.name, t.depth + 1 -- recursive: children of the last round
FROM categories c
JOIN tree t ON c.parent_id = t.id
)
SELECT * FROM tree ORDER BY depth, id;
-- id | parent_id | name | depth
-- 11 | 10 | Phones | 1
-- 12 | 10 | Laptops | 1
-- 13 | 11 | Android phones | 2
-- 14 | 13 | Rugged phones | 3
How the recursion builds the result
RoundInput rowsNew rows produced
Anchorcategories with parent_id = 1011 (depth 1), 12 (depth 1)
111, 1213 (depth 2), child of 11
21314 (depth 3)
314none, so the recursion stops
Each round only looks at the rows the previous round produced.

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.

SQL
WITH RECURSIVE tree AS (
SELECT id, parent_id, name, 1 AS depth FROM categories WHERE parent_id = 10
UNION ALL
SELECT c.id, c.parent_id, c.name, t.depth + 1
FROM categories c JOIN tree t ON c.parent_id = t.id
) CYCLE id SET is_cycle USING path
SELECT id, name, depth FROM tree WHERE NOT is_cycle;
-- Before PostgreSQL 14: track the path ourselves
-- ... , ARRAY[id] AS path ... in the anchor
-- ... , t.path || c.id ... WHERE c.id <> ALL(t.path) in the recursive part

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.

SQL
-- Move category 11 under category 14? 14 is a descendant of 11, so refuse.
WITH RECURSIVE sub AS (
SELECT id FROM categories WHERE id = 11
UNION ALL
SELECT c.id FROM categories c JOIN sub s ON c.parent_id = s.id
)
SELECT EXISTS (SELECT 1 FROM sub WHERE id = 14); -- true: the move would create a cycle

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.

Common ways to store a tree
ModelRead subtreeMove subtreeNotes
Adjacency listRecursive CTEOne updateSimple, the default
Materialized path (ltree)Prefix match, indexedRewrite paths in subtreePath like 1.10.11
Nested setsOne range queryRenumber much of the treeFast reads, costly writes
Closure tableOne indexed joinRows per ancestor pairFast 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.

What to say in the interviewAbout 90 seconds aloud

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.
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/