Model hierarchical data with a self-referencing foreign key — an adjacency list — as your default: each row stores its own parent_id, inserts and reparenting are single-row updates, and the one query that feels awkward (fetch every descendant of a node) is solved with a recursive query, not a schema redesign, for the vast majority of real trees.
Quick Answer: Default to an adjacency list (a
parent_idself-reference on the entity). Move to materialized path, nested set, or closure table only when a specific read pattern — deep descendant lookups at scale, or frequent subtree moves — makes the recursive query too slow or the join too awkward to live with.
Every nested-category picker, every org chart, every comment thread with replies-to-replies is the same shape underneath: a tree. Relational databases don't have a native tree type, so the pattern you choose to fake one decides, permanently, whether "get everything under this node" is a one-liner or a stored procedure nobody wants to touch. This is one of those decisions that looks cosmetic in the first sprint and structural eighteen months later.
Four Ways to Store a Tree in a Relational Database
Every hierarchy — nested categories, org charts, folder trees, threaded comments — reduces to one of four relational patterns: adjacency list, materialized path, nested set, and closure table. Each encodes the identical parent-child facts differently, trading insert simplicity against read speed, and the right choice depends entirely on which query you run most often.
Bill Karwin's widely-read book SQL Antipatterns devotes a full chapter to exactly this problem, framing the naive, under-indexed version of a parent-child table as an antipattern and walking through all four fixes below as the legitimate alternatives. That chapter is close to the canonical reference for this decision, and it's worth reading in full if you inherit a tree-shaped schema you didn't design.
| Pattern | Extra storage | Get direct children | Get all descendants | Move a subtree | Typical fit |
|---|---|---|---|---|---|
| Adjacency list | One parent_id column | Single indexed query | Recursive query or app-side loop | Update one row | Default for most trees |
| Materialized path | One path/string column | Prefix match (LIKE) | Prefix match (LIKE) | Rewrite the path on every descendant | Read-heavy, shallow-to-medium trees |
| Nested set | Two integers (lft, rgt) | Range query | Single range query, no recursion | Renumber a large span of the tree | Rarely-written, heavily-read trees |
| Closure table | A separate ancestor-descendant table | Depth = 1 filter | Single join, no recursion | Insert/delete closure rows for the moved node | Frequent moves and frequent descendant reads |
Read that table as a set of trade-offs, not a ranking. Nested set answers "all descendants" fastest but makes moving a subtree expensive. Adjacency list makes every write trivial but pushes the descendant query onto the read path. There is no pattern that wins on every axis — which is exactly why "just use the fancy one" is bad advice without a query to justify it.
The Adjacency List: Your Default Choice
Reach for the adjacency list first, every time, until a specific query proves it's not enough. Add a nullable, self-referencing foreign key — parent_id — to the entity's own table, and you get a fully valid tree with zero extra structures, standard referential integrity, and single-row inserts and reparenting operations.
For a nested-category schema, that's the whole model:
CREATE TABLE category (
id INT PRIMARY KEY,
name TEXT NOT NULL,
parent_id INT NULL REFERENCES category(id),
deleted_at TIMESTAMP NULL
);
CREATE INDEX idx_category_parent ON category(parent_id);
Fetching direct children — "what's under Laptops" — is a single indexed lookup:
SELECT id, name FROM category WHERE parent_id = 12;
Before you even get to the pattern question, decide whether Category deserves to be its own table at all, rather than a denormalized tag on Product — that's the judgment call walked through in what counts as an entity when modeling data. If categories have their own attributes, get reorganized independently of the products in them, or need their own permissions, they're an entity. If they're just a label, you may not need a tree at all.
A few practical notes worth locking in early:
- Index
parent_id. Without it, every children lookup and every recursive step degrades to a table scan once the table has more than a few hundred rows. - Make
parent_idnullable, not a self-pointing sentinel row, to represent the root — aNULLroot is unambiguous and plays well with foreign-key constraints. - Decide what happens on delete before you need to know. Deleting a category with children either cascades, orphans them (
parent_id = NULL), or is blocked — pick one deliberately, and if the entity is soft-deleted rather than hard-deleted, the tree logic has to account for a deleted parent whose children are still live. That exact tension is covered in soft delete vs. hard delete when modeling data, and it bites tree structures harder than flat tables because one deleted row can strand an entire branch. - Guard against cycles. A self-referencing FK alone doesn't stop someone from making a node its own great-grandparent; that has to be enforced in application logic or a trigger, since standard foreign-key constraints only check the immediate parent, not the whole chain.
The "Show All Subcategories" Query That Exposes the Choice
Fetching a node's direct children is trivial in every pattern; fetching every descendant at every depth is the query that actually tests your model. Adjacency lists need a recursive query or an application-side loop to walk the tree, while materialized path, nested set, and closure table all answer it with one flat, non-recursive statement.
On an adjacency list, "show all subcategories of Electronics" is a recursive common table expression:
WITH RECURSIVE subcategories AS (
SELECT id, name, parent_id
FROM category
WHERE id = 4 -- Electronics
UNION ALL
SELECT c.id, c.name, c.parent_id
FROM category c
JOIN subcategories s ON c.parent_id = s.id
)
SELECT * FROM subcategories WHERE id != 4;
That's not exotic SQL — WITH RECURSIVE has been in PostgreSQL since version 8.4 (2009), and MySQL added it in 8.0 (2018) — but plenty of ORMs still don't generate it for you, and older MySQL deployments (5.7 and earlier) can't run it at all. That gap is exactly why materialized path became popular for read-heavy trees on older MySQL: it gets the same answer with a plain, indexable string match.
| Pattern | Query for "all descendants of node 4" |
|---|---|
| Adjacency list | WITH RECURSIVE walking parent_id (above) |
| Materialized path | SELECT * FROM category WHERE path LIKE '1/4/%' |
| Nested set | SELECT * FROM category WHERE lft BETWEEN 8 AND 15 (parent's own lft/rgt) |
| Closure table | SELECT c.* FROM category c JOIN tree_paths t ON t.descendant_id = c.id WHERE t.ancestor_id = 4 |
Notice the pattern: three of the four options trade a recursive query for either a string match or a join against precomputed rows. That's the entire value proposition of materialized path, nested set, and closure table — they do the recursion once, at write time, so every read is flat.
Materialized Path and Closure Table: When You Need More
Upgrade past the adjacency list only when a concrete, measured read pattern demands it — deep trees queried constantly, or a UI that needs "breadcrumb from root" on every page load. Each alternative removes recursion from reads at the cost of making writes (especially moving a subtree) more expensive and more error-prone.
Materialized Path: Cheap Reads, Expensive Moves
Materialized path stores the full ancestor chain as a string on each row, like 1/4/9/. Joe Celko, who popularized much of the SQL hierarchy literature in his book Trees and Hierarchies in SQL for Smarties, documents this as "path enumeration."
It's cheap to read with a LIKE prefix match and cheap to understand at a glance. The trade-off: every descendant's path has to be rewritten when you move a subtree, and the string has a practical depth limit.
Nested Set: The Fastest Read, the Most Expensive Write
Nested set, also formalized by Celko, assigns two integers (lft, rgt) to each node so that a node's descendants all fall inside its own numeric range. It answers "all descendants," "all ancestors," and "is X inside Y's subtree" in a single range query with no joins at all — genuinely the fastest read of the four.
The cost shows up on write: inserting or moving a node means renumbering every lft/rgt value to its right, an operation that gets expensive fast on a large, frequently-reorganized tree.
Closure Table: The Most Flexible, at the Cost of a Second Table
Closure table, described in detail by Vadim Tropashko in SQL Design Patterns and covered alongside the other three in Karwin's chapter, stores every ancestor-descendant pair — including a node's relationship to itself — in a separate table:
CREATE TABLE tree_paths (
ancestor_id INT NOT NULL REFERENCES category(id),
descendant_id INT NOT NULL REFERENCES category(id),
depth INT NOT NULL,
PRIMARY KEY (ancestor_id, descendant_id)
);
It's the most flexible of the four — moving a subtree is a bounded delete-and-reinsert of that node's closure rows, not a full renumbering. The cost is a second table whose row count grows faster than the tree itself (a node ten levels deep has ten ancestor rows, not one). For a tree with frequent reorganizations and frequent descendant queries, it's usually the right trade.
Org Charts vs. Category Trees: Same Pattern, Different Pressures
An org chart and a product category tree use the identical adjacency-list schema — a self-referencing FK — but the queries that matter, and therefore the pattern that eventually makes sense, diverge based on how each tree actually gets used. Modeling the relationship correctly is only step one; knowing which reads to optimize for is step two.
Org Charts: Ancestor Chains and Cycle Prevention
An org chart typically needs three query shapes:
- Who reports to this manager (children)
- The full chain of command up to the CEO (ancestors)
- Everyone under a given VP regardless of depth (descendants)
Writes are infrequent here — reorgs happen in bursts, not continuously — which makes nested set's expensive move operation less painful than it looks on paper. Cycle prevention matters more than in a catalog, too: an adjacency list alone won't stop someone from becoming their own manager three levels up, so that check has to live in application logic, not the schema.
Category Trees: Read-Heavy at Scale
A product category tree is read-dominated in a different way: thousands of storefront page loads hitting "show everything under Electronics" for every one catalog reorganization. That imbalance is exactly the case for closure table or nested set — but only past a certain scale.
For a catalog with a few hundred categories, a recursive CTE (or a cached, precomputed descendant list refreshed on write) is often genuinely faster to ship and easier to reason about than a second table. Don't reach for the heavier pattern until the catalog and the traffic actually justify it.
The same tree shape shows up outside the database, too, wherever a product concept gets decomposed into a hierarchy for planning rather than storage:
- A JTBD job map — the main job with its related and sub-jobs, the structure covered in the complete guide to jobs to be done — is a tree the moment you persist it, not just a diagram.
- A customer journey broken into phases, stages, and touchpoints, as described in the complete guide to customer journey mapping, is the same nested structure with a different label on each node.
Recognizing the shape early — "this is a tree" — is what keeps you from reinventing adjacency lists badly as a bag of foreign keys pointing in inconsistent directions.
Modeling It in Practice
Pick the pattern by working backward from the one query that actually has to be fast, not from which pattern sounds more sophisticated. In practice that means a short, repeatable sequence rather than a one-time architectural debate.
- Draw the tree relationship on the ERD before writing a single
CREATE TABLE— the discipline argued for in why the data model is the product: draw the ERD first applies doubly to self-referencing relationships, since the self-reference is easy to miss when you're sketching quickly. - Start with the adjacency list. It's the least commitment: one column, one index, standard constraints.
- Name the query that would break it. Not "we might need fast descendant lookups someday" — an actual page, an actual report, an actual latency budget.
- Only then reach for materialized path, nested set, or closure table, matched to whichever column in the comparison table above your named query actually needs.
This whole decision is a specific instance of the broader modeling discipline covered in the complete guide to data modeling: get the entities and relationships right before optimizing for a query you haven't confirmed you need.
If you're working through this in Prodinja's Data Modelling tool, the self-reference is a first-class relationship type rather than a workaround: add a self-referencing relationship to an entity to model the parent-child tree directly on the canvas, and the tool renders the resulting foreign key in the generated DDL, exactly as it would look in the CREATE TABLE statement above. It's designed to make the adjacency-list default visible and easy to reason about, not to pick the pattern for you — that call still depends on your actual read pattern.
Key Takeaways
- Default to the adjacency list — a single
parent_idself-referencing foreign key — for any new hierarchical data; it's the least complex, most write-friendly of the four patterns. - All four patterns store identical facts; they differ only in whether the cost lands on reads (adjacency list) or writes (nested set, materialized path, closure table).
- "Show all descendants" is the query that exposes the choice — trivial as a flat
LIKEor range query in three of the four patterns, but a recursive query (or app-side loop) on an adjacency list. - Materialized path trades cheap prefix-match reads for expensive path rewrites whenever a subtree moves.
- Nested set gives the fastest possible descendant/ancestor reads via a single range query, at the cost of renumbering large ranges on every insert or move.
- Closure table handles frequent moves and frequent descendant queries better than the other three, at the cost of a second, faster-growing table.
- Don't upgrade past the adjacency list speculatively — name the specific slow query first, then match the pattern to it.
- Org charts and category trees share a schema but not a query profile; org charts need ancestor chains and cycle prevention, catalogs need fast bulk descendant reads at read-heavy scale.
Frequently Asked Questions
What is the best data model for a category tree?
For most nested-category schemas, an adjacency list — a parent_id self-referencing foreign key on the category table — is the best starting model. It's simplest to write to, keeps referential integrity intact, and only needs an upgrade if descendant queries at scale prove too slow.
Should I use adjacency list or nested set for hierarchical data?
Use adjacency list by default; move to nested set only when you have a read-heavy tree, deep or wide, where "get all descendants" or "get all ancestors" runs constantly and writes (inserts, subtree moves) are comparatively rare. Nested set optimizes reads at the direct expense of write cost.
How do I query all descendants of a node in SQL?
On an adjacency list, use a recursive common table expression (WITH RECURSIVE in PostgreSQL and MySQL 8.0+) that starts at the node and repeatedly joins children onto the growing result set. On materialized path, nested set, or closure table, the same query is a single non-recursive LIKE, range, or join query instead.
Does MySQL support recursive queries for hierarchies?
Yes, as of MySQL 8.0 (released 2018), via WITH RECURSIVE common table expressions — the same syntax PostgreSQL has supported since version 8.4 (2009). Earlier MySQL versions (5.7 and before) can't run recursive CTEs, which is a real factor in choosing materialized path or closure table on legacy deployments.
What is a closure table and when should I use one?
A closure table is a separate table storing every ancestor-descendant pair in a tree, including each node's relationship to itself, so descendant and ancestor queries become simple joins instead of recursion. Reach for it when a tree needs both frequent subtree moves and frequent descendant queries — the combination adjacency list and nested set each handle poorly.