Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

An HR platform stores 2 million employees and 50,000 org units. The most frequent queries are "all people under this org unit" and "is X in Y's chain" for authorization, and reorganizations move whole subtrees a few times a month. Compare adjacency list with recursive CTEs, materialized path, nested sets and closure tables, and pick one.

For hot subtree reads and is-X-in-Y's-chain checks with a few reorganisations a month, keep the adjacency list (parent_id) as the source of truth and maintain a closure table of org units alongside it in the same transaction, or an ltree path if we prefer one column. Recursive CTEs alone are too costly for authorization checks, nested sets are too expensive to move, and the closure table turns both frequent questions into single indexed lookups while a subtree move touches only a few thousand rows.

Why this question is asked

Hierarchy storage looks like a textbook topic until the hierarchy sits on the authorization path. Then every page load asks whether the current manager may see an employee, and a slow tree query becomes a slow product. Interviewers ask this at senior level to see whether we can compare the classic models on the workload actually described, with numbers, and pick one with a clear reason rather than reciting definitions. In this answer, we will size the workload, walk through the adjacency list, materialized path, nested sets and closure table with what each costs, pick a design, and see how to keep authorization correct while a subtree moves.

1Sizing the Workload First

The hierarchy that matters is the org unit tree: 50,000 units, perhaps 8 to 12 levels deep. The 2 million employees each belong to one unit, so all people under a unit means all units in a subtree joined to employees by org_unit_id. The authorization check, is X in Y's chain, becomes: is X's unit inside the subtree of the unit Y manages.

Reads dominate massively. Authorization checks may run thousands of times per second, while reorganisations happen a few times a month and move whole subtrees. So we should optimise reads and accept somewhat more expensive, but safe, moves.

2Adjacency List With Recursive CTEs

Each unit has a parent_id. It is the most natural model and the cheapest to change: moving a subtree updates exactly one row, the subtree's root. Its weakness is reading. A subtree query is a recursive CTE that runs one join per level, and an is-ancestor check walks up the chain one row at a time.

For a report run a few times a day that is perfectly fine. For an authorization check on every request, ten dependent index lookups per check add latency and load, and caching the answers becomes mandatory. So the adjacency list is a good source of truth but not a good read model for this workload.

3Materialized Path and Nested Sets

A materialized path stores each unit's full path from the root, such as 'root.eng.platform'. In PostgreSQL the ltree extension makes this a proper type with a GiST index, so the subtree of eng is path <@ 'root.eng', one index scan. With a plain text path, a B-tree prefix query such as path LIKE 'root/eng/%' does the same, given an index that supports prefix matching. The cost is on moves: moving eng under ops rewrites the path of every descendant unit.

Java
-- ltree: all units under eng
SELECT id FROM org_unit WHERE path <@ 'root.eng';
-- move the subtree rooted at root.eng.platform under root.ops
UPDATE org_unit
SET path = 'root.ops' || subpath(path, nlevel('root.eng.platform') - 1)
WHERE path <@ 'root.eng.platform';
-- root.eng.platform.db -> root.ops.platform.db

Nested sets number the tree in a depth-first walk, giving each node a left and right number, so a subtree is every node with lft between the root's lft and rgt. Reads are fast, but inserting or moving a node renumbers a large part of the whole tree, often half of it, and that renumbering takes locks across many rows. Nested sets suit trees that almost never change, such as a product taxonomy published once a quarter, not an org chart under active reorganisation.

4The Closure Table

A closure table stores every ancestor-descendant pair explicitly, including each unit with itself at depth 0. Both frequent questions become a single indexed lookup.

SQL
CREATE TABLE org_closure (
ancestor int NOT NULL REFERENCES org_unit(id),
descendant int NOT NULL REFERENCES org_unit(id),
depth int NOT NULL,
PRIMARY KEY (ancestor, descendant)
);
CREATE INDEX ON org_closure (descendant, ancestor);
-- all people under unit 40
SELECT e.* FROM org_closure c JOIN employee e ON e.org_unit_id = c.descendant
WHERE c.ancestor = 40;
-- is employee X's unit (812) inside manager Y's unit (40)?
SELECT EXISTS (SELECT 1 FROM org_closure WHERE ancestor = 40 AND descendant = 812); -- true
The four models on this workload
ModelSubtree readIs-ancestor checkSubtree move
Adjacency listrecursive CTE, one join per levelwalk up, about 10 lookupsupdate 1 row
Materialized path / ltreeone index range scanprefix test on 2 pathsrewrite all descendant paths
Nested setsone range scan on lftcompare lft and rgtrenumber much of the tree
Closure tableone indexed lookupone primary key lookupdelete and insert pairs

Storage grows with depth: each unit has one row per ancestor, so 50,000 units at an average depth of 8 give about 400,000 rows, which is small. Note that we put the closure on org units, not on 2 million employees; that keeps the table and the moves small. A move deletes the pairs that connect the subtree to its old ancestors and inserts pairs to its new ones.

5The Choice and How a Move Works

I would keep parent_id on org_unit as the source of truth and maintain org_closure from it, in the same transaction as every hierarchy change, through a stored procedure or a single service method. The adjacency list stays easy to reason about and to import from HR; the closure table serves reads. If the team prefers fewer tables, an ltree path column maintained the same way is an equally good read model, and checks are prefix tests. Either way, the authorization result for a session can be cached for a short time.

SQL
-- move subtree rooted at :node under :new_parent (self rows at depth 0 exist)
DELETE FROM org_closure
WHERE descendant IN (SELECT descendant FROM org_closure WHERE ancestor = :node)
AND ancestor NOT IN (SELECT descendant FROM org_closure WHERE ancestor = :node);
INSERT INTO org_closure (ancestor, descendant, depth)
SELECT sup.ancestor, sub.descendant, sup.depth + sub.depth + 1
FROM org_closure sup CROSS JOIN org_closure sub
WHERE sup.descendant = :new_parent AND sub.ancestor = :node;
UPDATE org_unit SET parent_id = :new_parent WHERE id = :node;
-- a subtree of 2,000 units under 6 ancestors: about 12,000 rows deleted and 12,000 inserted

Notice the size. Even a large reorganisation touches tens of thousands of rows, a fraction of a second of work, done a few times a month. That is a good trade for making every authorization check a single lookup.

6Follow-up questions

How would you keep authorization correct during a subtree move?

Do the closure update and the parent_id update in one transaction, so readers see either the old tree or the new one, never a half-moved tree, thanks to MVCC. Serialise moves with a lock, such as an advisory lock on the hierarchy, so two reorganisations cannot interleave. Then invalidate cached authorization results after commit, through an event or a version number on the hierarchy that cache keys include. Finally, decide with the business whether access changes take effect at the move's effective date, since HR moves are often scheduled in advance.

Why not put all 2 million employees into the closure table?

It would multiply the rows by depth, roughly 20 million, and a reorganisation would rewrite pairs for every person moved. Since people belong to units, a closure on units plus the employee.org_unit_id column answers the same questions with a much smaller table.

When would recursive CTEs alone be enough?

When reads are occasional, such as admin reports, or the authorization check is cached for a long time. Then the simplicity of a single parent_id column outweighs the extra read cost.

7Conclusion

In this answer, we sized the workload, saw that the adjacency list is cheap to update but slow for hot checks, that materialized paths and ltree give range scans but rewrite paths on moves, that nested sets suit rarely changing trees, and that a closure table makes subtree reads and is-ancestor checks single lookups. We chose parent_id as the source of truth with a transactionally maintained closure table on org units, and kept authorization correct across moves with one transaction, a lock and cache invalidation.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start from the workload: reads, and especially authorization checks, dominate, while subtree moves happen a few times a month. The adjacency list with parent_id is the simplest and moving a subtree is a one-row update, but every subtree read is a recursive CTE and every is-ancestor check walks up about ten levels, which is too much on the hot authorization path.

Then, if they want more

A materialized path, for example PostgreSQL's ltree with a GiST index, makes subtree queries an index range scan, but moving a subtree rewrites the path of every descendant. Nested sets give fast reads but renumber a large part of the tree on every insert or move, so they suit nearly static trees.

A closure table stores every ancestor and descendant pair, so both questions become one indexed lookup; the cost is storage proportional to depth and a move that deletes and inserts many pairs.

My choice would be parent_id on the org unit table as the source of truth, with a closure table on the 50,000 units, not on the 2 million people, maintained in the same transaction as each change. That is roughly 400,000 rows, and a large move touches maybe 25,000 rows.

Authorization results get a short cache invalidated on commit, and moves are serialised with a lock.

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.
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 "An HR platform stores 2 million employees and 50,000 org units. The most frequent...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/00d5df3004/